Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] was rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.
Hint:
Could do it in-place with O (1) extra space?
This problem is required to move the elements in the array to the right of the K-bit.
If k<= N, through observation can be found, through three steps can be required to complete:
① N-k The first bit of the array
② the array after K-bit inversion
③ to invert the whole array
However, if k>n, then need to take one more step, that is k=k%n.
The code is as follows:
class solution { Public:voidSwapint& A,int& B) {intTemp=a; A=b; B=temp; }void Reverse(intNums[],intBeginintEnd) { for(inti=begin,j=end;i<j;i++,j--) {swap (nums[i],nums[j]); } }voidRotateintNums[],intNintK) {intstep=k%n;Reverse(Nums,0, n-step-1);Reverse(nums,n-step,n-1);Reverse(Nums,0, N-1); }};
[Leetcode] Rotate Array