[LeetCode]Rotate Array
public class Solution { public void rotate(int[] nums, int k) { int length = nums.length; k = k % length; reverse(nums, 0, length - 1); reverse(nums, 0, k - 1); reverse(nums, k, length - 1); } public void reverse(int[] nums, int left, int right) { while (left < right) { int tmp = nums[left]; nums[left] = nums[right]; nums[right] = tmp; left ++; right --; } } }
慢速方法
public class Solution { public void rotate(int[] nums, int k) { int length = nums.length; k = k % length; if (k == 0) { return; } int[] record = new int[k]; int ind = 0; for (int i = length - k; i < length; i++) { record[ind++] = nums[i]; } for (int i = length - 1; i >= k; i--) { nums[i] = nums[i - k]; } for (int i = 0; i < k; i++) { nums[i] = record[i]; } } }