Friday, July 24, 2015

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

这一题很巧妙,暴力破解的思维是对array里面的元素进行移动,当时这样几乎要移动array里面所有的元素,但是array的 rotate是可以用reverse words in a string的思想去做的,通过reverse去操作array非常简单。 这样的方法做rotate的题目要记得能想到。 

还有一个点很重要,关于reverse函数的使用,reverse(v.begin() + i, v.end() +j) reverse的范围是 [i, j-1],这样在reverse一个容器里面的部分元素时要非常小心。

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        //sanity check
        if (nums.size() == 0) return;
        int mm = k % nums.size();
        int helper = nums.size() - mm;
        //reverse first part
        reverse(nums.begin(), nums.begin()+ helper);
        //reverse second part
        reverse(nums.begin() + helper, nums.end());
        //reverse the whole array
        reverse(nums.begin(), nums.end());
        return;
    }
};

No comments:

Post a Comment