189 Rotate Array
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.
Stunning Trick:
http://zhuixin8.com/2016/10/09/%E7%99%BD%E8%AF%9DLeetCode-189-Rotate-Array/
Rotate right:
- reverse the entire array
- reverse the [0, k-1]
- reverse the [k,n]
Rotate left:
- reverse the [0, k-1]
- reverse the [k, n]
- reverse the entire array
public class Solution {
public void reverse(int[] nums, int start, int end)
{
int temp;
if(start >= end)
{
return;
}
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
reverse(nums, start+1, end-1);
}
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length-1);
reverse(nums, 0, k-1);
reverse(nums, k, nums.length-1);
}
}
Other Solution
https://leetcode.com/articles/rotate-array/#approach-4-using-reverse-accepted