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?
最简单的和次简单都一次过,一个是耗时不耗内存;一个是不耗时耗内存,见code1.
code2是时间O(n),空间O(1)的方法。
class Solution {
public void rotate2(int[] nums, int k) {
int len = nums.length;
int tmp = 0;
if(len<=1)
return;
k = k % len;
for(;k>0;k--)
{
tmp = nums[len-1];
for(int i=len-1;i>0;i--)
nums[i] = nums[i-1];
nums[0] = tmp;
}
return;
}
public void rotate(int[] nums, int k) {
int len = nums.length;
if(len<=1)
return;
k = k % len;
int[] tmp = new int[k];
for(int i=len-k;i<len;i++)
{
tmp[i-len+k] = nums[i];
}
for(int i=len-k-1;i>=0;i--)
{
nums[i+k] = nums[i];
}
for(int i=0;i<k;i++)
{
nums[i] = tmp[i];
}
return;
}
}
class Solution {
private void swap(int[] nums, int i, int j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private void reverse(int st, int ed, int[] nums)
{
while(st<ed)
{
swap(nums,st,ed);
st ++ ;
ed -- ;
}
}
public void rotate(int[] nums, int k) {
int len = nums.length;
k = k % len;
if(k==0 || len <= 1)
return;
reverse(0,len-1,nums);
reverse(0,k-1,nums);
reverse(k,len-1,nums);
return ;
}
}