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

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

题目大意:

将数组整体向右移动k位,多出来的移到数组前面。

思路:

用一个新数组来替换它即可。

代码如下:

class Solution {
public:
    void rotate(vector& nums, int k) {
        if(k == 0 || nums.size() == 1 || nums.size() == 0)
            return;
        if(k > nums.size())
            k = k % nums.size();
        int i,count;
        count = 0;
        i = nums.size() - k;
        vector tmp;
        while(count != nums.size() )
        {
            if(i >= nums.size() )
            {
                i -= nums.size();
            }
            tmp.push_back(nums[i]);
            i++;
            count++;
        }
        
        nums.swap(tmp);
    }
};

2016-08-12 01:09:11