IMG_1576252692706.JPG

微信公众号:醉前端
关注可了解更多解题技巧。问题或建议,请公众号留言;

题目

给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
  • 示例 1:

输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4]

解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]

  • 示例 2:

输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]

答案

  • 解法1:
const rotate = (nums, k) => {
    for(var i = 0; i<k; i++){
        nums.unshift(nums.pop());
    }
    return nums;
}
  • 解法2:
const rotate = (nums, k) => {
    const n = nums.length;
    let tmpEnd = 0;
    let tmpPrev = 0;
    for(let i = 0; i<k; i++) {
        tmpEnd = nums[n-1];
        for(let r = 0; r<n; r++) {
            tmpPrev = nums[r];
            nums[r] = tmpEnd;
            tmpEnd = tmpPrev;
        }
    }
    return nums
};
  • 解法3:
const rotate = (nums, k) => {
    const n = nums.length;
    let reversePoint = n - k%n;
    reversePoint != 0 && (nums = nums.slice(reversePoint).concat(nums.slice(0, reversePoint)));
    return nums;
}
  • 解法4:
const rotate = (nums, k) => {
    const n = nums.length;
    let newArr = new Array(n);
    for(let i = 0;i<n; i++){
        newArr[(i+k)%n] = nums[i];
    }    
    for(let r = 0; r<n; r++){
        nums[r] = newArr[r];
    }  
    return nums  
}
每日更新一道算法题,加个关注呗老铁!
每日更新一道算法题,加个关注呗老铁!

醉前端
174 声望83 粉丝

Time is a bird forever on the ring......