LeetCode 189 - Rotate Array

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.

Solution 1:

public void rotate(int[] nums, int k) {
    int n = nums.length;
    if(n == 0) return;
    k %= n;
    if(k == 0) return;
    reverse(nums, 0, n-k-1);
    reverse(nums, n-k, n-1);
    reverse(nums, 0, n-1);
}

private void reverse(int[] nums, int start, int end) {
    for(int i=start; i<=(start+end)/2; i++) {
        swap(nums, i, start+end-i);
    }
}

private void swap(int[] nums, int i, int j) {
    int tmp = nums[i];
    nums[i] = nums[j];
    nums[j] = tmp;
}

 

Solution 2:


LeetCode 189 - Rotate Array_第1张图片
 

public void rotate(int[] nums, int k) {
    int n = nums.length;
    if(n == 0) return;
    k %= n;
    int d = n - k; //右移K位等于左移N-K位
    for(int i=0; i<gcd(d, n); i++) {
        int tmp = nums[i];
        int j = i;
        while(true) {
            int x = j + d;
            if(x >= n) {
                x -= n;
            }
            if(x == i) break;
            nums[j] = nums[x];
            j = x;
        }
        nums[j] = tmp;
    }
}

private int gcd(int a, int b) {
    while(b!=0) {
        int tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}

 

Reference:

http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf

你可能感兴趣的:(LeetCode)