189. Rotate Array (Easy)
https://leetcode.com/problems/rotate-array/
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input:[1,2,3,4,5,6,7]
and k = 3 Output:[5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right:[7,1,2,3,4,5,6]
rotate 2 steps to the right:[6,7,1,2,3,4,5]
rotate 3 steps to the right:[5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Solutions
1.
class Solution {
// Do 3 times of rotation
public void rotate(int[] nums, int k) {
if (nums == null || nums.length <= 1 || k == 0) {
return;
}
int len = nums.length;
// what if k > len
k = k % len;
inverse(nums, 0, len - 1);
inverse(nums, 0, k-1);
inverse(nums, k, len - 1);
}
public void inverse(int[] nums, int left, int right) {
while (left < right) {
swap(nums, left, right);
left++;
right--;
}
}
private void swap(int[] nums, int x, int y) {
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}
}
2.
class Solution {
// TODO, Improvement needed.
public void rotate(int[] nums, int k) {
if (nums == null || nums.length <= 1 || k == 0) {
return;
}
int len = nums.length;
// what if k > len
k = k % len;
// for len = 4, k = 2, move elements of which index >=2, that is 2, 3
for (int i = len - 1; i >= len - k; i--) {
int tmp = nums[len - 1];
for (int j = len - 2; j >= 0; j--) {
nums[j + 1] = nums[j];
}
nums[0] = tmp;
}
}
}