Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array is [1,2,3,4,5,6,7]
rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.
[Show hint]
Hint:
Could do it in-place with O (1) extra space?
Related Problem:reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
"Idea One"
This topic means moving n = (k%nums.length) elements at the tail of the array to the front of the array. One of the simplest ideas is to move the next n elements forward in turn. The code is as follows:
1 Public classSolution {2 Public voidRotateint[] Nums,intk) {3 if(nums==NULL|| Nums.length <= 0)return;4 intn = k%nums.length;5 6 for(inti = 0; I < n; i++){7 for(intj = nums.length-n + i; J > i; j--){8 inttemp = Nums[j-1];9NUMS[J-1] =Nums[j];TenNUMS[J] =temp; One } A } - } -}
The complexity of the space is O (1), but the complexity of the time is high, how to improve it?
"Thinking Two"
For example: [1,2,3,4,5,6,7] k = 3
The array that first flips 5 of the data before it is [4,3,2,1,5,6,7]
The resulting array of 5 and later data is [4,3,2,1,7,6,5]
The entire array is then flipped to get [5,6,7,1,2,3,4]
The code is as follows:
1 Public classSolution {2 Public voidRotateint[] Nums,intk) {3 if(nums==NULL|| Nums.length <= 0 | | k%nums.length==0)return;4 intLength =nums.length;5K = k%length;6 7Reversal (nums, 0, length-k-1);8Reversal (Nums, length-k, length-1);9Reversal (nums, 0, Length-1);Ten } One Public voidReversal (int[] Nums,intIintj) { A intt = 0; - while(I < J && I >= 0){ -t =Nums[i]; theNums[i] =Nums[j]; -NUMS[J] =T; -i++; -j--; + - } + } A}
Leetcode OJ 189. Rotate Array