zoukankan      html  css  js  c++  java
  • 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);
           }
        }
    };


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

  • 相关阅读:
    CAST()类型转换函数
    CLR LOH的危险
    保持积极的态度,态度决定一切!
    as 操作符和强行转换的区别
    查内存覆盖从以前的帖子里总结的
    CLR中的范型为什么不支持很多操作符?
    如何做一个好的Team Leader?
    Dispose Pattern总结
    慎用Reflection
    CLR Enum类型内幕
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965364.html
Copyright © 2011-2022 走看看