成都创新互联网站制作重庆分公司

leetCode189.RotateArray数组

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

题目大意:

将数组整体向右移动k位,多出来的移到数组前面。

思路:

用一个新数组来替换它即可。

代码如下:

class Solution {
public:
    void rotate(vector& nums, int k) {
        if(k == 0 || nums.size() == 1 || nums.size() == 0)
            return;
        if(k > nums.size())
            k = k % nums.size();
        int i,count;
        count = 0;
        i = nums.size() - k;
        vector tmp;
        while(count != nums.size() )
        {
            if(i >= nums.size() )
            {
                i -= nums.size();
            }
            tmp.push_back(nums[i]);
            i++;
            count++;
        }
        
        nums.swap(tmp);
    }
};

2016-08-12 01:09:11


网页名称:leetCode189.RotateArray数组
转载注明:http://cxhlcq.com/article/ghieij.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部