您的位置:首页 > 其它

LeetCode(67)-Rotate Array

2016-04-21 12:24 387 查看

题目:

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].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.


思路:

题意:要求对给定长度的整形数组n进行平移,给定k,就平移3个位置(循环)

要求是在o(1)的空间,不能考虑数组的复制了,根据算法,这个平移转化为逆序。reverse(nums,0,n-k-1),reverse(nums,n-k,n-1),reverse(nums,0,n-1)等价,写一个reverse的函数。

代码:

public class Solution {
public void reverse(int[] nums,int start,int end){
while(start < end){
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
public void rotate(int[] nums, int k) {
if(nums.length == 0){
return;
}
int n = nums.length;
k = k%n;
reverse(nums,0,n-k-1);
reverse(nums,n-k,n-1);
reverse(nums,0,n-1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: