您的位置:首页 > 其它

rotate array

2016-03-28 13:27 453 查看
leetcode试题如下:

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array
[1,2,3,4,5,6,7]
is
rotated to
[5,6,7,1,2,3,4]
.
很简单的一道题,本来我自己想的是将数组复制然后在进行处理(具体的代码就不在赘述,实在是无颜见人,时间复杂度为O(n),只是在测试的时候发现runtime只是胜过了11.7%的人,以我的水平估计并没能优化。
然后在Discuss中发现简单并且优雅的算法,其时间复杂度为o(n)其空间复杂度为o(1),备受启发,特将java版本贴出来:

public class Solution {

public void rotate(int[] nums, int k) {

int length = nums.length;

k=k%length; // 这里他可能给出的k>length所以要特别处理一下

this.reverse(nums, 0, length-k-1);

this.reverse(nums, length-k, length-1);

this.reverse(nums, 0, length-1);

}

public void reverse(int[] nums, int l, int r){

while (l < r) {

int temp = nums[l];

nums[l] = nums[r];

nums[r] = temp;

l++;

r--;

}

}

}

这个程序的思路相当不错,大概为三个步骤:

Step 1 - 12345 6789 ---> 54321 6789

Step 2 - 54321 6789 ---> 54321 9876

Step 3 - 543219876 ---> 678912345

然而我测试的结果依然只是1ms和我的写法是一样的依然只战胜了11.7%的人,囧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: