问题重复:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入:[1,2,3,4,5,6,7]
和 k = 3 输出:[5,6,7,1,2,3,4]
解释: 向右旋转 1 步:[7,1,2,3,4,5,6]
向右旋转 2 步:[6,7,1,2,3,4,5]
向右旋转 3 步:[5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99]
和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
解决方案:
刚开始想了个暴力解决,一步步来,每次只向右走一次,结果提交发现超出时间了,对于太长的测试用例,时间估计就爆炸了,因为是O(nums.lenth^2);
从网上看了final_solution.好像也差点意思。。。。时间也是过长了点。不过压线通过了
public class rotate {
public int[] rorate_solution(int[] nums, int k){
int len = nums.length;
for (int i=0; i<k; i++){
nums = little_rorate(nums);
}
return nums;
}
public int[] little_rorate(int [] nums){
int len = nums.length;
int temp2 = nums[0];
if(len == 1){
return nums;
}
for (int i=0,temp; i<len; i++){
temp = nums[(i+1)%len];
nums[(i+1)%len] = temp2;
temp2 = temp;
}
return nums;
}
public int[] final_solution(int[] nums, int k){
int temp1, temp2, count = 0;
for (int i=0; i<k; i++){
if (count == nums.length){
return nums;
}
int index = i;
temp1 = nums[i];
while ((index + k)%nums.length != i){ //不是回到原点的话
temp2 = nums[(index+k)%nums.length];
nums[(index+k)%nums.length] = temp1;
temp1 = temp2;
index = (index+k)%nums.length;
count++;
}
nums[i] = temp1; //形成回环更新
count++;
}
return nums;
}
public static void main(String[] args){
rotate test = new rotate();
int[] test_arr = new int[]{1,2,3,4,5,6,7};
// int[] test_arr = new int[]{1};
int[] out;
// out = test.little_rorate(test_arr);
// out = test.rorate_solution(test_arr, 3);
out = test.final_solution(test_arr,3);
System.out.println(Arrays.toString(out));
}
}