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次
C++(19ms):
1 class Solution { 2 public: 3 void Reverse(vector<int>& nums,int left , int right){ 4 while(left < right){ 5 swap(nums[left++],nums[right--]) ; 6 } 7 } 8 void rotate(vector<int>& nums, int k) { 9 int len = nums.size() ; 10 k %= len ; 11 k = len - k ; 12 Reverse(nums,0,k-1) ; 13 Reverse(nums,k,len-1) ; 14 Reverse(nums,0,len-1) ; 15 } 16 };