leetCode 189. Rotate Array 数组

发布时间:2020-05-28 05:32:54 作者:313119992
来源:网络 阅读:357

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<int>& 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<int> 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

推荐阅读:
  1. [LeetCode]26. Remove Duplicates from Sorted Array
  2. leetCode 121. Best Time to Buy and Sell Stock 数组

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

数组 tc 18

上一篇:ViewPager如下效果你研究过吗

下一篇:【音视频】Android CallKit 开发指南

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》