Given a list of integers array we want to rotate the numbers to the right K times
Example
[1,2,3,4,5] k = 3
Ans:
[3,4,5,1,2]
Solution
This problem can be solved as follows.
- Reverse the entire array.
- Reverse the first k elements of the array.
- Reverse the remaining elements of the array.
public class Solution {
public void Rotate(int[] nums, int k) {
if (nums == null || nums.Length <= 1 || k % nums.Length == 0) return;
k %= nums.Length;
Reverse(nums, 0, nums.Length - 1);
Reverse(nums, 0, k - 1);
Reverse(nums, k, nums.Length - 1);
}
private void Reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}