首页 > 其他 > 详细

[LeetCode] Rotate Array

时间:2015-07-17 08:21:58      阅读:118      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!