leetcode------Rotate Array
标题: | Rotate Array |
通过率: | 18.4% |
难度: | 简单 |
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.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
第一种思路,k等于多少就循环多少次:意思是若k=3则所有元素向后移动三次,越界的则进行放在第一位操作,
具体看代码:
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 int length=nums.length; 4 int value=0; 5 for(int i=0;i<k;i++){ 6 value=nums[length-1]; 7 for(int j=nums.length-2;j>=0;j--){ 8 nums[j+1]=nums[j]; 9 } 10 nums[0]=value; 11 } 12 } 13 }
上述思路明显不是高效的,下面对数据进行分析,
1.2.3.4.5
当k=3时结果是3,4,5,1,2
把结果逆序下 可以看出来是 2,1,5,4,3逆序结果与正序进行对比
1,2,3,4,5
2,1,5,4,3
发现在k-1的位置前后都是逆序的,
第二种分析。
原数据逆序
5,4,3,2,1
3,4,5,1,2
也是在k-1位置前后进行逆序,
那么我只用对原数据做如下操作就可得到结果:
1、原数据逆序
2,k-1之前逆序
3,k-1之后逆序
直接看代码:
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 int length=nums.length; 4 k%=length; 5 res(nums,0,length-1); 6 res(nums,0,k-1); 7 res(nums,k,length-1); 8 9 } 10 public void res(int []arraynum,int start,int end){ 11 while(start<=end){ 12 int temp=arraynum[start]; 13 arraynum[start]=arraynum[end]; 14 arraynum[end]=temp; 15 start++; 16 end--; 17 } 18 } 19 }