小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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]

Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II

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

分析

数组旋转问题。

给定一个序列和一个整数,要求将序列元素右旋k位。题目不难,但是需要注意的一点是k值可能大于序列长度,所以,旋转之前先求k对序列长度size的余数即可。

该题目一个简单的解决方法是三次反转:

  1. 将序列中(0 , size-k-1)元素反转;
  2. 将序列中(size-k , size-1)元素反转;
  3. 将全序列(0,size-1)反转;

    即可完成要求!

AC代码

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if (nums.empty())
            return;

        int size = nums.size();

        //确定最终右旋元素个数

        k %= size;

        vector<int>::iterator beg = nums.begin();
        //旋转0~(size-k) (size-k , size);
        reverse(beg, beg + size - k);
        reverse(beg + size - k, nums.end());
        //最后一次全部反转,即可完成
        reverse(beg, nums.end());
    }
};

GitHub测试程序源码

posted on 2015-11-02 20:17  Coding菌  阅读(109)  评论(0编辑  收藏  举报