[Copy question]:
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]
.
[Brute force solution]:
Time Analysis:
Spatial Analysis:
[After optimization]:
Time Analysis:
Spatial Analysis:
[Wonderful output CONDITIONS]:
[Wonderful corner case]:
[Thinking questions]:
- The swap function is forgotten, and it's drunk.
- K-Step may be large, so%= array length is required
[a sentence of thought]:
[input]: null: Normal: Large: Extra Small: Special cases handled in the program: abnormal conditions (unreasonable input):
[Drawing]:
From left to right:
[One brush]:
- The swap function needs to be brought into index, so the internal I J does not need to be initialized
[Two brushes]:
[Three brushes]:
[Four brushes]:
[Five brushes]:
[Results of five-minute visual debug]:
[Summary]:
Reverse are all using the Swap function, and the routines are the same.
[Complexity]:time Complexity:o (n) Space complexity:o (1)
[English data structure or algorithm, why not other data structures or algorithms]:
[Key templating code]:
Swap
Public void swap (intint int j) { while (i < j) { int temp = nums[i]; = Nums[j]; = temp; I+ +; J--; }
[Other solutions]:
[Follow up]:
[The problem given by the LC becomes variable]:
All the questions of swap
[Code Style]:
classSolution { Public voidRotateint[] Nums,intk) {//cc if(Nums = =NULL|| Nums.length = = 0) { return ; } //INI, KK%=nums.length; //SwapSwap (nums, 0, nums.length-k-1); Swap (nums, Nums.length-K, Nums.length-1); Swap (Nums,0, Nums.length-1); //return } Public voidSwap (int[] Nums,intIintj) { while(I <j) {inttemp =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=temp; I++; J--; } }}
View Code
189. Rotate array from right to start flipping arrays