189. Rotate Array

Description

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?

Related problem:

Reverse Words in a String II

Solution

简单的反转再反转。time O(n), space O(1)。

class Solution {
    public void rotate(int[] nums, int k) {
        if (k <= 0) {
            return;
        }
        
        int n = nums.length;
        k %= n;  // in case k > n
        rotate(nums, 0, n - k - 1);
        rotate(nums, n - k, n - 1);
        rotate(nums, 0, n - 1);
    }
    
    public void rotate(int[] nums, int begin, int end) {
        while (begin < end) {
            int tmp = nums[begin];
            nums[begin++] = nums[end];
            nums[end--] = tmp;
        }
    }
}

你可能感兴趣的:(189. Rotate Array)