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.

思路： space O(1)解法，time O(n), 经典的**三步翻转法**. 先找到offset k % n

public class Solution {
public void rotate(int[] nums, int k) {
if (nums.length == 0 || nums == null) return;
int n = nums.length;
k %= n; // offset
reverseString(nums, 0, n - 1);
reverseString(nums, 0,k - 1);
reverseString(nums, k,n - 1);
}
public void reverseString(int [] nums, int low, int high) {
while (low < high) {
int tmp = nums[high];
nums[high] = nums[low];
nums[low] = tmp;
low++;
high--;
}
}
}

### Like this:

Like Loading...