There is no record of the problem. Rotating an array in place can be seen in programming Zhu Ji Nanxiong, which can also be found in JDK code (COLLECTIONS.ROTATE), which provides two ways to do three reverse and one is to perform traversal substitution.
The first way:
1 classSolution {2 Public:3 voidRotateintNums[],intNintk) {4 if(nums = = NULL | | n <=1) {5 return;6 }7K = k%N;8Reverse (Nums,0, n);9Reverse (Nums,0, k);Ten reverse (nums, K, n); One } A - voidReverseintNums[],intStartintend) { - intp =start; the intQ = end-1; - while(P <q) { - swap (Nums[p], nums[q]); -p++, q--; + } - } +};
The second way:
1 classSolution {2 Public:3 voidRotateintNums[],intNintk) {4K = k%N;5 intCNT =N;6 for(intCycle_start =0; Cnt cycle_start++) {7 inti = (cycle_start + k)%N;8 intreplaced =Nums[cycle_start];9 Ten while(I! =Cycle_start) { One swap (replaced, nums[i]); Ai = (i + k)%N; -cnt--; - } theNums[cycle_start] =replaced; -cnt--; - } - } +};
For the second way, if N and K are coprime, a while loop can be done
Leetcode Rotate Array Rotation