HappyLeetcode50:Rotate Array

來源:互聯網
上載者:User

標籤:

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

這道題雖然做了出來,但是顯然不是最優解。顯然空間要求沒有達到。

有一點要尤為注意,在一開始的時候我就預設k是小於n的,實際上k可以大於n,所以在修改代碼之後,我們所使用的k要對n取餘。

我的思路是,把數組中前面的值先挪到後面去。後面的值在被替換之前先存進一個vector裡面去,待前面的值安排完畢之後,把vector之中的資料取出,放在新數組的前面。

代碼如下:

class Solution {public:    void rotate(int nums[], int n, int k) {                if (nums == NULL || n <= 0 )            return;                k = k%n;        vector<int> TempSave;        TempSave.reserve(k);        int count = 0;//記錄已經推進了多少個資料        for (int i = n - k - 1; i >= 0; --i)        {            if (count < k){                TempSave.push_back(nums[i + k]);                count++;            }            nums[i + k] = nums[i];        }        int Temp = TempSave.size();        if (TempSave.size() < k)        {            for (int i = k - 1; i >= Temp; --i)                TempSave.push_back(nums[i]);        }        for (int i = 0; i < k; ++i)        {            nums[i] = TempSave.back();            TempSave.pop_back();        }        }};

其實後來想想還是有更簡單一些的方法,比如先把數組複製一遍,再根據情況裁剪出你需要的那一部分數組出來。

class Solution {public:    void rotate(int nums[], int n, int k) {        k = k % n;        int* NewNums =new int[n * 2];        for (int i = 0; i < n ; ++i)        {            NewNums[i] = nums[i];            NewNums[i + n] = nums[i];        }        //int res = n - k;        for (int i = 0; i < n; ++i)        {            nums[i] = NewNums[i + n - k];        }    }};
代碼量明顯短了不少。

HappyLeetcode50:Rotate Array

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.