码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 07 - Rotate Array

时间:2016-01-09 07:33:32      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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)

Jan 07 - Rotate Array

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5115399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!