2

前端刷力扣 - 189. 旋转数组[中等]

 2 years ago
source link: https://segmentfault.com/a/1190000040678981
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

刷题小白遇到这一题:

发现一个有趣,但是不是最好的方法。因为这个方法的效率一般:

但是思路很有意思

如:
nums = [1,2,3,4,5,6,7]
k = 3
可以这么操作。

  1. 把数组整个反转,为: [7,6,5,4,3,2,1]
  2. 从0到k-1反转,为:[5,6,7,4,3,2,1]
  3. 从k到最后反转,为:[5,6,7,1,2,3,4]
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    k = k > nums.length ? k % nums.length : k;
    
    reverse(nums, 0, nums.length - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, nums.length - 1);
};

function reverse(nums, i, j) {
    while(i < j) {
        swap(nums, i, j);
        i++;
        j--;
    }
}

function swap(nums, i, j) {
    let temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

题目在这里https://leetcode-cn.com/probl...
有兴趣的同学可以去评论里面看看最高效的实现方式。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK