LeetCode - 189. Rotate Array - 思路詳解 - C++

題目

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

翻譯

給定一個n個元素的數組,所有元素向右移動k步。

思路

假設len爲數組長度。

思路1,採用分部旋法,首先旋轉0~len-k元素,然後在旋轉len-k ~ 最後一個元素。最後將整個數組旋轉。即可將所有元素向右旋轉k個位置

思路2,暴力法,開闢一個數組,然後遍歷當前數組,將第i個元素放置到 i+k%len 位置處。

代碼

//思路1
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k > nums.size()){
            k = k % (nums.size());
        }

        std::reverse(nums.begin(),nums.end()-k);
        std::reverse(nums.end()-k,nums.end());
        std::reverse(nums.begin(),nums.end());
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章