溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

leetCode 189. Rotate Array 數(shù)組

發(fā)布時(shí)間:2020-05-28 05:32:54 來源:網(wǎng)絡(luò) 閱讀:357 作者:313119992 欄目:編程語言

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.

題目大意:

將數(shù)組整體向右移動k位,多出來的移到數(shù)組前面。

思路:

用一個(gè)新數(shù)組來替換它即可。

代碼如下:

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI