public class Solution { public void rotate(int[] nums, int k) { int n = nums.length; k = k % n; int[] res = new int[n]; for (int i = 0; i < n; i++) { res[(i + k)%n] = nums[i]; } for (int i = 0; i < n; i++) { nums[i] = res[i]; } } }
这样space complexsion 不是O(1)
时间空间复杂度:http://blog.csdn.net/zolalad/article/details/11848739
参考答案:
直接观察规律,类似三部反转法。
public void rotate(int[] nums, int k) { if (nums.length == 0) { return; } k = k % nums.length; reverse(nums, 0, nums.length - k - 1); reverse(nums, nums.length - k, nums.length - 1); reverse(nums, 0, nums.length - 1); } public void reverse(int[] nums, int start, int end) { while (start < end) { int tmp = nums[start]; nums[start] = nums[end]; nums[end] = tmp; start++; end--; } }
原文:http://www.cnblogs.com/77rousongpai/p/4509089.html