leetcode 189. Rotate Array

题目描述:

解题

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

        int i = 0;
        int j = nums.size()-1;
        if(nums.size() < k){
            k = k % nums.size();
        }

        reverse(nums,i,j);
        reverse(nums,i,k-1);
        reverse(nums,k,j);
        
    }
    
    void reverse(vector<int> &nums, int start,int end){
        if(start == end)
            return;
        while(start < end ){
            int tmp = nums[start];
            nums[start++] = nums[end];
            nums[end--] = tmp;
        }
    }
};

 

posted @ 2017-05-10 21:09  StrongYaYa  阅读(161)  评论(0编辑  收藏  举报