leetcode 189. Rotate Array

題目描述:spa

解題code

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;
        }
    }
};
相關文章
相關標籤/搜索