Skip to content

Latest commit

 

History

History
50 lines (38 loc) · 1.18 KB

数组旋转.md

File metadata and controls

50 lines (38 loc) · 1.18 KB

向右移动k步

  1. 使用slice

[1,2,3,4,5,6,7]向右移动 3 步的结果为[5, 6, 7, 1,2, 3, 4]

function rotateArray(arr, k){
    const len = arr.length
    if(k < 0 || k === 0 || k === len) return arr
    if(k > len) k = k % len
    return arr.slice(-k).concat(arr.slice(0, arr.length-k))
    // return [...arr.splice(len - k), ...arr]
}

const arr = [1,2,3,4,5,6,7]

console.log(rotateArray(arr,-1)) // [1,2,3,4,5,6,7]
console.log(rotateArray(arr,0)) // [1,2,3,4,5,6,7]
console.log(rotateArray(arr,7)) // [1,2,3,4,5,6,7]
console.log(rotateArray(arr,3)) // [5, 6, 7, 1,2, 3, 4]

arr.slice()可以接收负数索引,从倒数第n个值开始截取

  1. 使用popunshift进行移动模拟

频繁的移动数组,效率很差

function rotateArray(arr, k){
    const len = arr.length
    if(k < 0 || k === 0 || k === len) return arr
    for (let index = 0; index < k; index++) {
        arr.unshift(arr.pop())        
    }
    return arr
}
function rotateArray(arr, k){
    const len = arr.length
    if(k < 0 || k === 0 || k === len) return arr
    new Array(k).fill('').forEach(() => arr.unshift(arr.pop()))
    return arr
}