|
| 1 | +difficulty level: Medium |
| 2 | +class Solution { |
| 3 | +public: |
| 4 | + void rotate(vector<int>& nums, int k) { |
| 5 | + int n = nums.size(); |
| 6 | + k = k % n; |
| 7 | + // we first reverse all the elements,[7 6 5 4 3 2 1] |
| 8 | + for (int i = 0, j = n - 1; i < j; i++, j--) { |
| 9 | + swap(nums[i], nums[j]); |
| 10 | + } |
| 11 | + // then we reverse the set of elements sized k for example [7 6 5 4 3 2 1] = [ 5 6 7 4 3 2 1] |
| 12 | + for (int i = 0, j = k - 1; i < j; i++, j--) { |
| 13 | + swap(nums[i], nums[j]); |
| 14 | + } |
| 15 | + //finally we reverse the ending elements too = 5 6 7 1 2 3 4 |
| 16 | + for (int i = k, j = n - 1; i < j; i++, j--) { |
| 17 | + swap(nums[i], nums[j]); |
| 18 | + } |
| 19 | + } |
| 20 | +}; |
| 21 | + |
| 22 | +Time complexity:O(n) |
| 23 | +Space Complexity:O(1) |
| 24 | +/* |
| 25 | +Input: nums = [1,2,3,4,5,6,7], k = 3 |
| 26 | +Output: [5,6,7,1,2,3,4] |
| 27 | + |
| 28 | +Example 2: |
| 29 | + |
| 30 | +Input: nums = [-1,-100,3,99], k = 2 |
| 31 | +Output: [3,99,-1,-100] |
| 32 | +*/ |
0 commit comments