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]
.
Topic:
Gives an array, n elements, moves the array to the right to move the k elements in a loop.
Ideas:
Note that the requirements of the topic are circular movement, so k can be any non-negative integer, but the number of array elements is n, so k=k%n.
A common idea is to:
1. Flip the entire array: a[0...n-1]; e.g. [7,6,5,4,3,2,1]
2, flip the array before K: a[0,k-1], such as [5,6,7,4,3,2,1]
3, flip the array after n-k: a[k,n-1], such as [5,6,7,1,2,3,4]
Similar applications: Flip all the words in a sentence, and the word content does not change.
Code:
classSolution { Public: voidReverseintNums[],intIintj) { while(i<j) { inttmp=Nums[i]; Nums[i]=Nums[j]; NUMS[J]=tmp; I++; J--; } } voidRotateintNums[],intNintk) {k=k%N; if(k>=1&& n>1&& k<=N) {Reverse (nums,0, N-1); Reverse (Nums,0, K-1); Reverse (Nums,k,n-1); } }};
(Leetcode 189) Rotate Array