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]
.public class Solution { public void rotate(int[] nums, int k) { if (nums == null || nums.length == 0) { return; } int n = nums.length; if (k > n) { k = 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 left, int right) { if (left > right) { return; } int start = left; int end = right; while (start < end) { int tem = nums[start]; nums[start] = nums[end]; nums[end] = tem; start++; end--; } } }
没有评论:
发表评论