1. Question
Rotate an arrayNElements to the rightKSteps.
For example,N= 7 andK= 3, the array[1,2,3,4,5,6,7]Is rotated[5,6,7,1,2,3,4].
Note:
Try to come up as your solutions as you can, there are at least 3 different ways to solve this problem.
[Show hint]
Hint:
Cocould You Do It In-Place with O (1) extra space?
Credits:
Special thanks to @ freezen for adding this problem and creating all test cases.
The hide tags array 2 idea was previously viewed in "programming Pearl". First, the first part is rotated, then the last part is selected, and then the whole part is rotated. The result is displayed. the time complexity O (N ), space O (1) is a good algorithm. It can be used to move a row in a text editor. 3 code
Public void rotate (INT [] Nums, int K) {int Len = nums. length; K % = Len; // it is important to prevent K from exceeding Len this. partrotate (Nums, 0, len-k); this. partrotate (Nums, len-K, Len); // as to why not Len-k-1 is related to the following implementation. This. partrotate (Nums, 0, Len);} public int [] partrotate (INT [] Nums, int head, int rear) {int temp = 0; For (INT I = 0; I <(rear-head)/2; I ++) {temp = Nums [head + I]; Nums [head + I] = Nums [rear-I-1]; nums [rear-I-1] = temp;} return Nums ;}
[Leetcode 189] rotate Array