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

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

一:三次翻转,c++stl中就有这个算法

class Solution {
public:
    void reverse(vector<int>& nums,int startPos,int endPos)
    {
        int i=startPos,j=endPos-1;
        while(i<j){
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
            i++;j--;
        }
    }
    void rotate(vector<int>& nums, int k) {
        if(k<=0){
            return;
        }
        int numsSize = nums.size();
        k = k%numsSize;
        reverse(nums,0,numsSize-k);
        reverse(nums,numsSize-k,numsSize);
        reverse(nums,0,numsSize);
    }
};

2:使用一个辅助空间O(k)的辅助空间

代码不多说,太简单

3:递推计算每个字符的位置,循环n次

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k<=0){
            return;
        }
        int numsSize = nums.size();
        int start = 0,i=0;
        while(i<numsSize){
            int nextIndex = (start+k)%numsSize;
            int curVal = nums[start];
            while(nextIndex!=start){
                int tmp = nums[nextIndex];
                nums[nextIndex] = curVal;
                curVal = tmp;
                nextIndex = (nextIndex+k)%numsSize;
                i++;
            }
            nums[nextIndex] = curVal;
            i++;
            start++;
        }
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/4959358.html