码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Rotate Array

时间:2015-07-17 08:23:43      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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

[LeetCode] Rotate Array

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4653377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!