您的位置:首页 > 其它

LeetCode OJ 189. Rotate Array

2016-05-19 17:52 302 查看
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.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

【思路一】

这个题目的意思是把数组尾部的n = (K%nums.length)个元素移动到数组的前面。一个最简单的想法就是把后面n个元素依次往前移动即可。代码如下:

public class Solution {
public void rotate(int[] nums, int k) {
if(nums==null || nums.length <= 0) return;
int n = k % nums.length;

for(int i = 0; i < n; i++){
for(int j = nums.length - n + i; j > i; j--){
int temp = nums[j-1];
nums[j-1] = nums[j];
nums[j] = temp;
}
}
}
}


这样做空间复杂度为O(1),但是时间复杂度较高,如何改进呢?

【思路二】

例如:[1,2,3,4,5,6,7] k = 3

先将5以前的数据翻转得到的数组是[4,3,2,1,5,6,7]

再将5及以后的数据翻转得到的数组是[4,3,2,1,7,6,5]

再将整个数组翻转即得到[5,6,7,1,2,3,4]

代码如下:

public class Solution {
public void rotate(int[] nums, int k) {
if(nums==null || nums.length <= 0 || k%nums.length==0) return;
int length = nums.length;
k = k%length;

reversal(nums, 0, length - k - 1);
reversal(nums, length -k, length - 1);
reversal(nums, 0, length - 1);
}
public void reversal(int[] nums, int i, int j){
int t = 0;
while(i < j  && i >= 0){
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
i++;
j--;

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: