189. Rotate Array

来源:互联网 发布:json 汉字编码 编辑:程序博客网 时间:2024/05/16 05:43

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.

[show hint]

Related problem: Reverse Words in a String II

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

Subscribe to see which companies asked this question

分析:

根据编程珠玑入门,对数组A旋转前i个数,可以换个理解方式将A看作ab.

其中a是前i个数,b是剩下的数,等效为(ab)转换为ba.

((a)'(b)')'=ba。因此将a先翻转,再将b翻转,最后将前两部结果翻转即可以得到ba。

代码:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int t=k%nums.size();
        int n=nums.size();
        if(t>0)
        {
            int left=0;
            int right=n-t-1;
            while(left<right)
            swap(nums[left++],nums[right--]);
            left=n-t;right=n-1;
            while(left<right)
            swap(nums[left++],nums[right--]);
            left=0;right=n-1;
            while(left<right)
            {swap(nums[left++],nums[right--]);}
        }
    }
};


0 0
原创粉丝点击