Leetcode - Rotate Array

Question

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

Hint

Could you do it in-place with O(1) extra space?

Java Code

//版本一:多次反转
public void rotate(int[] nums, int k) {
    int n = nums.length;
    //数组长度小于2或循环右移步数k正好是数组长度的整数倍,则数组不变
    if(n < 2 || (k %= n) == 0) return;

    //前n-k个数组元素反转
    reverseArray(nums, 0, n-k-1);

    //后k个数组元素反转
    reverseArray(nums, n-k, n-1);

    //整个数组反转
    reverseArray(nums, 0, n-1);
}

public void reverseArray(int[] nums, int low, int high) {
    int temp;
    int medium = (low + high + 1)/2;
    for(int i = low; i < medium; ++i) {
        temp = nums[i];
        nums[i] = nums[low + high - i];
        nums[low + high - i] = temp;
    }
}

//版本二:数组拷贝
public void rotate2(int[] nums, int k) {
    int n = nums.length;
    if(n < 2 || (k %= n) == 0) return;

    //拷贝得到原数组的一个副本
    int[] numsNew = new int[n];
    System.arraycopy(nums, 0, numsNew, 0, n);

    //拷贝回原数组得到循环右移k步之后的元素
    System.arraycopy(numsNew, 0, nums, k, n - k);
    System.arraycopy(numsNew, n - k, nums, 0, k);
}

说明

  • 本题的实质是实现数组的循环右移。第一种方法不使用任何额外的空间,共交换n次实现了数组的循环移位,这个做法比较巧妙,可以模拟验证一下其正确性;第二种方法需要额外的O(1)空间,我们分析得到循环移位之后数组元素的局部顺序保持不变,所以可以通过数组的分段拷贝一步到位实现循环移位,实测表明其效率比多次反转更高。

你可能感兴趣的:(LeetCode,rotate,循环移位)