The rotate operation of the array for a given number of times.
Rotate once: The end element is placed at the beginning, and the other elements are cycled to the right one unit.
Ideas
1. Open a space where the k elements at the end are placed in the beginning of the new array in the previous order, and the remaining elements of the original array are assigned to the remaining space in the new array in the order of the former.
It saves time complexity and increases the complexity of space.
2. Forward thinking, each processing once rotate, the last element bubbles to the beginning. The complexity of the time is too high.
3. Replace the rotate with an exchange, the array is divided into two halves, the first half is flipped, the second half is flipped, the final whole is flipped, the time complexity and space complexity are the lowest.
"My Code"
voidRotateintNums[],intNintk) {intk1=k%N; Reverse (Nums,0, n-k1-1); Reverse (nums, n-K1, N-1); Reverse (Nums,0, N-1); } voidReverseintNums[],intLinth) { //swap instead of flipping inttemp; intMid= (L+H)/2; for(intI=l; i<=mid; i++) {Temp=Nums[i]; Nums[i]=nums[h-i+L]; Nums[h-i+l]=temp; } }
PostScript
Time consuming 27ms, ranked top.
So, the previously learned algorithm is still useful, inadvertently will be remembered.
OJ Practice 36--t189 Rotate Array