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] .
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.
[Show hint]
Related Problem:reverse Words in a String II
[Solution]
Save A[k, n-1] to temporary space, move a[0, K-1]. O (k) Secondary storage
voidRotate (vector<int>& Nums,intk) {intn =nums.size (); if(n = =0|| K <=0) return; K= k%N; Vector<int> buf (k,0); for(inti =0; I < K; i++) Buf[i]= Nums[n-k +i]; for(inti = n-1; I >= K; i--) Nums[i]= Nums[i-K]; for(inti =0; I < K; i++) Nums[i]=Buf[i]; }
In situ Exchange:
The array consists of AB two parts, moving K positions to form a BA
Use R (a) to indicate the reverse order of a, then there is R (R (a)) = a
R (AB) = R (B) R (A)
Then R (B), R (A) are reversed to get BA
1 voidRotate (vector<int>& Nums,intk)2 {3 intn =nums.size ();4 if(n = =0|| K <=0)5 return;6 7K = k%N;8Reverse (Nums,0N1);9Reverse (Nums,0K1);TenReverse (nums, K, N-1); One } A - voidReverse (vector<int>& Nums,intSinte) - { the for(inti = s, j = e; I < J; i++, j--) - swap (Nums[i], nums[j]); -}
[Leetcode 189] Rotate Array