您的位置:首页 > 其它

LeetCode-Rotate Array

2015-03-06 00:00 288 查看
摘要: https://oj.leetcode.com/problems/rotate-array/
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.
Hint:
Could you do it in-place with O(1) extra space?

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

这道题目比较简单,不过要考的是面试的时候能否想到尽可能多的算法并且具有空间和时间的高效性。

一开始想到一个空间O(1)的算法,但是明显太慢了,所以在遇到一个超长的测试数据时RLE了。这个空间O(1)的算法用的就是每次移动一格,这样子只需要一个临时数据就可以存储了。

class Solution {
public:
void rotate(int nums[], int n, int k) {
if (((k%=n) == 0)||n==1)return;
int tmp;
while(--k){
rolling(nums,n);
}
}

void rolling(int nums[], int n){
int tmp = nums[--n];
while(--n){
nums[n+1] = nums
;
}
nums[0] = tmp;
}
};

另一种方法,用一个辅助的数组很容易就可以通过。

class Solution {
public:
void rotate(int nums[], int n, int k) {
if((k%=n)==0||n==1)return;
int* tmp = new int
;
for(int i = k; i < n;++i)tmp[i] = nums[i-k];
for(int i = 0; i < k;++i)tmp[i] = nums[n-k+i];
for(int i = 0; i < n; ++i)nums[i] = tmp[i];
}
};

题目要求想出至少3个方法,这才第一个。第二个方法比较逗,我了解到C++标准库里就有一个rotate函数,运算结果发现速度也不是特别快。

class Solution {
public:
void rotate(int nums[], int n, int k) {
if((k%=n)==0||n==1)return;
std::rotate(nums,nums+n-k,nums+n);
}
};

如何在O(1)的空间里完成这个呢?

根据大神 3 lines of C++ in one pass using swap,的方法确实做到了O(1)space,只是不太好理解。

按sample 1,2,3,4,5,6,7 -> 3 应该是 5,6,7,1,2,3,4,按照算法

5,2,3,4,1,6,7
5,6,3,4,1,2,7
5,6,7,4,1,2,3
---------n-=k==4 k%=n==3
5,6,7,1,4,2,3
5,6,7,1,2,4,3
5,6,7,1,2,3,4
--------n-=k==1 k%=n==0
DONE!!!

class Solution {
public:
void rotate(int nums[], int n, int k) {
for (; k %= n; n -= k)
for (int i = 0; i < k; i++)
swap(*nums++, nums[n - k]);
}
};

其实一开始我也想到这样子,但是不知道如何有效地组织指针的移动,通过这个案例算是学到了不少。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode oj