silver-hands / sss

0 stars 0 forks source link

【Q058】189. 旋转数组 #58

Open fly0o0 opened 4 years ago

fly0o0 commented 4 years ago

189. 旋转数组

fly0o0 commented 4 years ago
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    let n = nums.length

    k %= n

    if(n === 1){
        return
    }

    nums = myReverse(nums, 0, n - 1)

    nums = myReverse(nums, 0, k - 1)

    nums = myReverse(nums, k, n - 1)
};

function myReverse(nums, start,end) {
    while (start < end) {
       let tmp = nums[start];
        nums[start] = nums[end];
        nums[end] = tmp;
        start++;
        end--;
    }
    return nums
}