标签:
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)
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5115399.html