Rotate Array【翻转数组】

PROBLEM:

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

SOLVE(C++):

#1.Time complexity: O(n). Space complexity: O(1).

class Solution{
public:
    void rotate(int nums[], int n, int k){
        if ((n == 0) || (k <= 0))
            return;
        int cntRotated = 0;
        int start = 0;
        int curr = 0;
        int numToBeRotated = nums[0];
        int tmp = 0;
        while (cntRotated < n){
            do{
                tmp = nums[(curr + k)%n];
                nums[(curr+k)%n] = numToBeRotated;
                numToBeRotated = tmp;
                curr = (curr + k)%n;
                cntRotated++;
            } while (curr != start);
            start++;
            curr = start;
            numToBeRotated = nums[curr];
        }
    }
};

解释:第1个数移动到第k个元素位置,原第k个移动到第2k个...循环时注意取余;如果循环到初始位置则向后移动一个位置并开始重复之前的移动,最后n个元素全被移动过就结束。

#2.Time complexity: O(n). Space complexity: O(1).

class Solution{
public:
    void rotate(int nums[], int n, int k){
        k = k%n;
        reverse(nums, nums + n - k);
        reverse(nums + n - k, nums + n);
        reverse(nums, nums + n);
    }
};

解释:将前n-k个元素组成的数组翻转,将后k个元素组成的数组翻转,最后将整个数组翻转

#3.Time complexity: O(n). Space complexity: O(1).

class Solution {
public:
    void rotate(vector& nums, int k) {
        int n = nums.size();
        if (k%n == 0) return;
        int first = 0, middle = n-k%n, last = n;
        int next = middle;
        while(first != next) {
            swap (nums[first++], nums[next++]);
            if (next == last) next = middle;
            else if (first == middle) middle = next;
        }
    }
};
解释:将后k个元素与前k个元素交换,然后将下标为k(变量first)~(n-k-1)(变量middle前一个元素)的元素整体换到末尾。算法中保证middle始终 在first后,而next不断在middle和next之间循环(next为超尾)

你可能感兴趣的:(数据结构与算法)