您的位置:首页 > 其它

leetcode [Rotate Array]//待整理多种解法

2017-04-08 23:51 489 查看
public class Solution {
//解法一:利用一个辅助数组可以要求,但不是很好,题目要求空间复杂度是O(1)的
public void rotate(int[] nums, int k) {
//题目要求:Rotate an array of n elements to the right by k steps.
//先处理k的值,鲁棒性
k = k % nums.length;
int[] temp = new int[nums.length];
for(int i = nums.length - k, j = 0, shift = k; shift > 0; i++, j++, shift--){
temp[j] = nums[i];
//System.out.println((j + 1) + " : " + temp[j]);
}
for(int i = 0, j = k; i < nums.length - k; i++, j++){
temp[j] = nums[i];
//System.out.println((j + 1) + " : " + temp[j]);
}
//nums = temp;//最后把temp赋值给nums,这样不行,因为nums只是一个对象引用的拷贝,要修改nums只能直接去操作对象
for(int i = 0; i < nums.length; i++){
nums[i] = temp[i];
}
}
}


下面这种解法遇到长数组会很耗时

public class Solution {
//解法二:Rotate an array of n elements to the right by k steps.将右边的k个数与左边的nums.length-k个数整体交换
//其实就是将数组看成一个环状的,要达到这样的目的其实就是将右边的k个数往左推nums.length-k格,观察例子总结
//因为将数组看成一个环状的,那么左边的k个数也从右开始向左推
//空间复杂度是O(1),只用到了一个temp,但时间复杂度是O(N*k)
public void rotate(int[] nums, int k) {
if(nums.length == 0) return;
k = k % nums.length;//鲁棒性
for(int i = 0; i < nums.length - k; i++){//记录要移动的步数,左推nums.length-k格而不是k格
int temp = nums[0];//因为要移动,要存一个被覆盖的数
for(int j = 0; j < nums.length - 1; j++){
nums[j] = nums[j + 1];
}
nums[nums.length - 1] = temp;//末尾元素
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: