移动数组中元素,双指针

124 阅读1分钟

普通方法: Array.splice

// arr : Array [] , 源数组
// index: Number , 移动元素下标
// tindex: Number , 目标位置下标 
function move (arr, index, tindex) {
    if (index > tindex) {
        arr.splice(tindex, 0, arr[index]);
        arr.splice(index+1, 1);
    } else {
        arr.splice(tindex+1, 0, arr[index]);
        arr.splice(index, 1);
    }
}

双指针:arr[index], arr[j]

// arr : Array [] , 源数组
// index: Number , 移动元素下标
// tindex: Number , 目标位置下标 
function move2(arr, index, tindex) {
    if (index < tindex) {
        let j = index+1;
        while (index < tindex){
            [arr[j], arr[index]] = [arr[index], arr[j]];
            j++; index++;
        }
    } else {
        let j = index-1;
        while (index > tindex) {
            [arr[index], arr[j]] = [arr[j], arr[index]];
            j--; index--;
        }
    }
    return arr;
}

测试样例:

let arr1 = [1,2,3,4,5,6,7];
let arr2 = [1,2,3,4,5,6,7];

move(arr1, 5, 1);
move2(arr2, 5, 1);
console.log(arr1, '打印move');
console.log(arr2, '打印move2');

move(arr1, 1, 5);
move2(arr2, 1, 5);
console.log(arr1, '打印move');
console.log(arr2, '打印move2');