public class Solution {
public void rotate(int[] nums, int k) {
if(nums.length < 2) return;
k = k % nums.length;
if(k == 0) return;
int tail = 0;
for(int i = 1; i <= k; i++){
tail = nums[nums.length-1];
for(int j = 1; j < nums.length; j++){
nums[j] = nums[j-1];
}
nums[0] = tail;
}
}
}

Time Limit Exceeded!!!

看来不能用brute force,想想其他方法吧。

 

public class Solution {
public void rotate(int[] nums, int k) {
if(nums.length < 2) return;
k = k % nums.length;
if(k == 0) return;
int count = 0;
int i = 0;
while(count < nums.length){
count += switchPos(i, k, nums);
i++;
}
}

public int switchPos(int i, int k, int[] nums){
int temp = nums[i];
int start = i;
int count = 0;
while((i-k)!=start){
if(i < k){
nums[i] = nums[nums.length+i-k];
i = nums.length+i-k;
}
else{
nums[i] = nums[i-k];
i = i - k;
}
count++;
}
nums[i] = temp;
return ++count;
}
}

Runtime: O(n)

posted on 2016-01-09 07:17  爱推理的骑士  阅读(88)  评论(0编辑  收藏  举报