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

leetcode - Rotate Array

时间:2015-05-13 18:48:33      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

 1 class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         vector<int> res;
 5         //vector<int>::iterator it1 = nums.begin();
 6         if(k==0) return;
 7         vector<int>::iterator it2 = nums.begin() + (nums.size() - k%nums.size());
 8         vector<int>::iterator it = it2;
 9         while(it!=nums.end()){
10             res.push_back(*it);
11             it++;
12         }
13         it = nums.begin();
14         while(it!= it2){
15             res.push_back(*it);
16             it++;
17         }
18         nums = res;
19     }
20 };

然而这个方法空间复杂度为n,还有一种空间复杂度为1的版本:

class Solution {
public:
    void rotate(int nums[], int n, int k) {
        k = k % n;
        reverse(nums, nums + n);
        reverse(nums, nums + k);
        reverse(nums + k, nums + n);
    }
};

 先把AB reverse一次得到reverse(B)reverse(A)

然后再把reverse(B),reverse(A)分别reverse一次就得到了BA

 

很巧妙。

leetcode - Rotate Array

标签:

原文地址:http://www.cnblogs.com/shnj/p/4501001.html

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