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; } } };
幸运之神的降临,往往只是因为你多看了一眼,多想了一下,多走了一步。