|
| 1 | +/* |
| 2 | +Given an array, rotate the array to the right by k steps, where k is non-negative. |
| 3 | +
|
| 4 | +Follow up: |
| 5 | +
|
| 6 | +Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. |
| 7 | +Could you do it in-place with O(1) extra space? |
| 8 | +
|
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: nums = [1,2,3,4,5,6,7], k = 3 |
| 13 | +Output: [5,6,7,1,2,3,4] |
| 14 | +Explanation: |
| 15 | +rotate 1 steps to the right: [7,1,2,3,4,5,6] |
| 16 | +rotate 2 steps to the right: [6,7,1,2,3,4,5] |
| 17 | +rotate 3 steps to the right: [5,6,7,1,2,3,4] |
| 18 | +Example 2: |
| 19 | +
|
| 20 | +Input: nums = [-1,-100,3,99], k = 2 |
| 21 | +Output: [3,99,-1,-100] |
| 22 | +Explanation: |
| 23 | +rotate 1 steps to the right: [99,-1,-100,3] |
| 24 | +rotate 2 steps to the right: [3,99,-1,-100] |
| 25 | +
|
| 26 | +
|
| 27 | +Constraints: |
| 28 | +
|
| 29 | +1 <= nums.length <= 2 * 10^4 |
| 30 | +It's guaranteed that nums[i] fits in a 32 bit-signed integer. |
| 31 | +k >= 0 |
| 32 | +
|
| 33 | +
|
| 34 | +
|
| 35 | +Solution one using brute force, it does not work in C++ |
| 36 | +Two using extra space |
| 37 | +Three using rotation. |
| 38 | +*/ |
| 39 | +class Solution { |
| 40 | +public: |
| 41 | + void rotate(vector<int>& nums, int k) { |
| 42 | + int size = nums.size(); |
| 43 | + k = k % size; |
| 44 | + if( k == 0 ) return; |
| 45 | + int temp, previous; |
| 46 | + for ( int i = 0; i < k; i++ ) |
| 47 | + { |
| 48 | + previous = nums[size - 1]; |
| 49 | + for ( int j = 0; j < size; j++ ) |
| 50 | + { |
| 51 | + temp = nums[j]; |
| 52 | + nums[j] = previous; |
| 53 | + previous = temp; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | +}; |
| 58 | + |
| 59 | +class Solution { |
| 60 | +public: |
| 61 | + void rotate(vector<int>& nums, int k) { |
| 62 | + int size = nums.size(); |
| 63 | + k = k % size; |
| 64 | + if ( k == 0 ) return; |
| 65 | + vector<int> temp( size ); |
| 66 | + for ( int i = 0; i < size; i++ ) |
| 67 | + { |
| 68 | + temp[ ( i + k ) % size ] = nums[i]; |
| 69 | + } |
| 70 | + nums = temp; |
| 71 | + } |
| 72 | +}; |
| 73 | + |
| 74 | +class Solution { |
| 75 | +public: |
| 76 | + void rotate(vector<int>& nums, int k) { |
| 77 | + int size = nums.size(); |
| 78 | + k = k % size; |
| 79 | + if( k == 0 ) return; |
| 80 | + int count = 0; |
| 81 | + //We need this loop as when ( curr + k ) % size = 0, the array may not be fully rotated. |
| 82 | + for ( int i = 0; count < size; i++ ) |
| 83 | + { |
| 84 | + int curr = i; |
| 85 | + int prev = nums[i]; |
| 86 | + do |
| 87 | + { |
| 88 | + int next = ( curr + k ) % size; |
| 89 | + int temp = nums[next]; |
| 90 | + nums[next] = prev; |
| 91 | + curr = next; |
| 92 | + prev = temp; |
| 93 | + count++; |
| 94 | + } while( i != curr ); |
| 95 | + } |
| 96 | + } |
| 97 | +}; |
0 commit comments