184.Rotate Array

题目:

Given an array, rotate the array to the right by k steps, where k is non-negative.

给定一个数组,将数组向右旋转k步,其中k为非负数。

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.尝试尽可能多地提出解决方案,至少有3种不同的方法可以解决这个问题。
  • Could you do it in-place with O(1) extra space?你能用O(1)额外空间就地做到吗?

解答:

 方法一:用O(1)的额外空间,但是O(n2)的时间复杂度,太慢了

 1 class Solution {
 2     public void rotate(int[] nums, int k) {
 3         for(int i=0;i<k;i++)
 4             rotateOneStep(nums);
 5         return;
 6     }
 7     
 8     private void rotateOneStep(int[] nums){
 9         int n=nums.length;
10         int lastNum=nums[n-1];
11         for(int i=n-1;i>0;i--)
12             nums[i]=nums[i-1];
13         nums[0]=lastNum;
14     }
15 }

方法二:O(n)空间复杂度——利用辅助数组

 1 class Solution {
 2     public void rotate(int[] nums, int k) {
 3         int n=nums.length;
 4         int[] tempNums=new int[n];
 5         for(int i=0;i<n;i++)
 6             tempNums[i]=nums[i];
 7         for(int i=0;i<n;i++)
 8             nums[(i+k)%n]=tempNums[i];  //(i+k)%n即为旋转后i元素的新位置
 9     }
10 }

方法三:类似翻转字符串

 1 class Solution {
 2     public void rotate(int[] nums, int k) {
 3         int n=nums.length;
 4         if(nums.length==0 || (k%=n)==0) return; //k%=n使得k一定小于n,如果为0则不需要旋转
 5         reverse(nums,0,n-k-1);
 6         reverse(nums,n-k,n-1);
 7         reverse(nums,0,n-1);
 8     }
 9     
10     private void reverse(int[] nums,int start,int end){
11         while(start<end){
12             int temp=nums[start];
13             nums[start]=nums[end];
14             nums[end]=temp;
15             start++;
16             end--;
17         }
18     }
19 }

详解:

 方法三分析:n=7,k=3

0 1 2 3 4 5 6   坐标

1 2 3 4 5 6 7    原数组

4 3 2 1 5 6 7    前n-k个数字翻转 [0,n-k-1]

4 3 2 1 7 6 5    后k个数字翻转 [n-k,n-1]

5 6 7 1 2 3 4    整个字符串翻转 [0,n-1]

注意k可能大于n,例如nums=[1,2],k=3,旋转3位相当于旋转3%2=1位

posted @ 2018-09-21 09:48  chan_ai_chao  阅读(113)  评论(0编辑  收藏  举报