Leecode | Rotate Array



Rotate Array

 Total Accepted: 26104 Total Submissions: 146721My Submissions

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.











题目说多想几种方法,额,目前只想到一个好像==,而且WA了n多次。。。

我的思路:将旋转后的左半部分和右半部分分别存起来,然后清空原来的数组,push进去左半部分和右半部分,就得到目标数组了。还有其他方法,我想到并且AC了再补充。。

程序:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
       if(k==0) return;
       while(k<0) k+=nums.size();
       if(k>nums.size()) k%=nums.size();
       vector<int> temp1;   //两部分,分别存vector的前部分和后部分
       vector<int> temp2;
       vector<int>::iterator lam;
       for(lam=nums.begin();lam!=nums.end();lam++)
       {
           temp1.push_back(*lam);
       }
       for(int i=0;i<k;i++)
       {
           temp2.push_back(temp1.back());
           temp1.pop_back();
       }
       nums.clear();  //清空
       vector<int>::reverse_iterator p=temp2.rbegin();
       for(;p!=temp2.rend();p++)
       {
           nums.push_back(*p);
       }
       vector<int>::iterator pp=temp1.begin();
       for(;pp!=temp1.end();pp++)
       {
           nums.push_back(*pp);
       }
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-05-25 15:02  Tob__yuhong  阅读(140)  评论(0编辑  收藏  举报

导航