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

S1:Make an extra copy and then rotate. Time complexity: O(n). Space complexity: O(n).

S2: Start from one element and keep rotating until we have rotated n different elements. Time complexity: O(n). Space complexity: O(1). 需要记录开始rotate的位置,一旦形成环要选择一个数重新开始

S3: 两遍reverse:Reverse the first n - k elements, the last k elements, and then all the n elements. Time complexity: O(n). Space complexity: O(1).

注意reverse的范围是[first,last) ,不包括last

    void rotate(vector<int>& nums, int k) {
        k = k % nums.size();
        reverse(nums.begin(), nums.end());
        reverse(nums.begin(), nums.begin()+k);//reverse range: [first,last)
        reverse(nums.begin()+k, nums.end());
    }

results matching ""

    No results matching ""