[LeetCode] Rotate Array

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.

 1 class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         int n = nums.size();
 5         k %= n;
 6         reverse(nums.begin(), nums.begin() + n - k);
 7         reverse(nums.end() - k, nums.end());
 8         reverse(nums.begin(), nums.end());
 9     }
10 };

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

1 class Solution {
2 public:
3     void rotate(vector<int>& nums, int k) {
4         int start = 0, n = nums.size();
5         for (; k %= n; n -= k, start += k)
6             for (int i = 0; i < k; i++)
7                 swap(nums[start + i], nums[start + n - k + i]);
8     }
9 };

For a more comprehensive summary of other solutions, you may refer to this link (it has 5 solutions).

posted @ 2015-07-17 07:04  jianchao-li  阅读(162)  评论(0编辑  收藏  举报