您的位置:首页 > 其它

[LeetCode] Rotate Array

2015-07-17 07:04 369 查看
This problem, as stated in the problem statement, has a lot of solutions. Since the problem requires us to solve it in O(1) space complexity, I only show some of them in the following.

The first one, also my favorite one, is to apply reverse to nums for three times. You may run some this code on some examples to see how it works.

class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n;
reverse(nums.begin(), nums.begin() + n - k);
reverse(nums.end() - k, nums.end());
reverse(nums.begin(), nums.end());
}
};


The second one is to use swap, and is translated from the C code in this link.

class Solution {
public:
void rotate(vector<int>& nums, int k) {
int start = 0, n = nums.size();
for (; k %= n; n -= k, start += k)
for (int i = 0; i < k; i++)
swap(nums[start + i], nums[start + n - k + i]);
}
};


For a more comprehensive summary of other solutions, you may refer to this link (it has 5 solutions).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: