[LeetCode] 189. Rotate Array 旋轉數組

 

Given an array, rotate the array to the right by k steps, where k is non-negative.html

Example 1:git

Input:  and k = 3
Output: 
Explanation:
rotate 1 steps to the right: 
rotate 2 steps to the right: rotate 3 steps to the right: 
[1,2,3,4,5,6,7][5,6,7,1,2,3,4][7,1,2,3,4,5,6][6,7,1,2,3,4,5][5,6,7,1,2,3,4]

Example 2:github

Input:  and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
[-1,-100,3,99]

Note:算法

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.數組

 

新題搶先刷,這道題標爲 Easy,應該不是很難,咱們先來看一種 O(n) 的空間複雜度的方法,咱們複製一個和 nums 同樣的數組,而後利用映射關係 i -> (i+k)%n 來交換數字。代碼以下:post

 

解法一:this

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        vector<int> t = nums;
        for (int i = 0; i < nums.size(); ++i) {
            nums[(i + k) % nums.size()] = t[i];
        }
    }
};

 

因爲提示中要求咱們空間複雜度爲 O(1),因此咱們不能用輔助數組,上面的思想仍是可使用的,可是寫法就複雜的多,並且須要用到不少的輔助變量,咱們仍是要將 nums[idx] 上的數字移動到 nums[(idx+k) % n] 上去,爲了防止數據覆蓋丟失,咱們須要用額外的變量來保存,這裏用了 pre 和 cur,其中 cur 初始化爲了數組的第一個數字,而後固然須要變量 idx 標明當前在交換的位置,還須要一個變量 start,這個是爲了防止陷入死循環的,初始化爲0,一旦當 idx 變到了 strat 的位置,則 start 自增1,再賦值給 idx,這樣 idx 的位置也改變了,能夠繼續進行交換了。舉個例子,假如 [1, 2, 3, 4], K=2 的話,那麼 idx=0,下一次變爲 idx = (idx+k) % n = 2,再下一次又變成了 idx = (idx+k) % n = 0,此時明顯 1 和 3 的位置尚未處理過,因此當咱們發現 idx 和 start 相等,則兩者均自增1,那麼此時 idx=1,下一次變爲 idx = (idx+k) % n = 3,就能夠交換完全部的數字了。url

由於長度爲n的數組只須要更新n次,因此咱們用一個 for 循環來處理n次。首先 pre 更新爲 cur,而後計算新的 idx 的位置,而後將 nums[idx] 上的值先存到 cur 上,而後把 pre 賦值給 nums[idx],這至關於把上一輪的 nums[idx] 賦給了新的一輪,完成了數字的交換,而後 if 語句判斷是否會變處處理過的數字,參見上面一段的解釋,咱們用題目中的例子1來展現下面這種算法的 nums 的變化過程:spa

1 2 3 4 5 6 7
1 2 3 1 5 6 7
1 2 3 1 5 6 4
1 2 7 1 5 6 4
1 2 7 1 5 3 4
1 6 7 1 5 3 4
1 6 7 1 2 3 4
5 6 7 1 2 3 4code

 

解法二:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if (nums.empty() || (k %= nums.size()) == 0) return;
        int start = 0, idx = 0, pre = 0, cur = nums[0], n = nums.size();
        for (int i = 0; i < n; ++i) {
            pre = cur;
            idx = (idx + k) % n;
            cur = nums[idx];
            nums[idx] = pre;
            if (idx == start) {
                idx = ++start;
                cur = nums[idx];
            }
        }
    }
};

 

根據熱心網友 waruzhi 的留言,這道題其實還有種相似翻轉字符的方法,思路是先把前 n-k 個數字翻轉一下,再把後k個數字翻轉一下,最後再把整個數組翻轉一下:

1 2 3 4 5 6 7
4 3 2 1 5 6 7
4 3 2 1 7 6 5
5 6 7 1 2 3 4

 

解法三:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if (nums.empty() || (k %= nums.size()) == 0) return;
        int n = nums.size();
        reverse(nums.begin(), nums.begin() + n - k);
        reverse(nums.begin() + n - k, nums.end());
        reverse(nums.begin(), nums.end());
    }
};

 

因爲旋轉數組的操做也能夠看作從數組的末尾取k個數組放入數組的開頭,因此咱們用 STL 的 push_back 和 erase 能夠很容易的實現這些操做。

 

解法四:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if (nums.empty() || (k %= nums.size()) == 0) return;
        int n = nums.size();
        for (int i = 0; i < n - k; ++i) {
            nums.push_back(nums[0]);
            nums.erase(nums.begin());
        }
    }
};

 

下面這種方法其實還蠻獨特的,經過不停的交換某兩個數字的位置來實現旋轉,根據網上這個帖子的思路改寫而來,數組改變過程以下:

1 2 3 4 5 6 7
5 2 3 4 1 6 7
5 6 3 4 1 2 7
5 6 7 4 1 2 3
5 6 7 1 4 2 3
5 6 7 1 2 4 3
5 6 7 1 2 3 4

 

解法五:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if (nums.empty()) return;
        int n = nums.size(), start = 0;   
        while (n && (k %= n)) {
            for (int i = 0; i < k; ++i) {
                swap(nums[i + start], nums[n - k + i + start]);
            }
            n -= k;
            start += k;
        }
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/189

 

相似題目:

Rotate List

Reverse Words in a String II 

 

參考資料:

https://leetcode.com/problems/rotate-array/

https://leetcode.com/problems/rotate-array/discuss/54250/Easy-to-read-Java-solution

https://leetcode.com/problems/rotate-array/discuss/54277/Summary-of-C%2B%2B-solutions

https://leetcode.com/problems/rotate-array/discuss/54438/My-c%2B%2B-solution-o(n)time-andand-o(1)space

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索