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] .
Although this problem has been done, it is obviously not the optimal solution. Obviously space requirements are not met.
One thing to pay particular attention, in the beginning I was the default k is less than N, in fact, K can be greater than n, so after modifying the code, we use K to the N to take the remainder.
My idea is to move the previous value in the array first to the back. The following values are stored in a vector before being replaced, and after the previous values are arranged, the data in the vector is taken out and placed in front of the new array.
The code is as follows:
classSolution { Public: voidRotateintNums[],intNintk) {if(nums = = NULL | | n <=0 ) return; K= k%N; Vector<int>Tempsave; Tempsave.reserve (k); intCount =0;//record how much data has been pushed. for(inti = n-k-1; I >=0; --i) {if(Count <k) {Tempsave.push_back (nums[i+K]); Count++; } nums[i+ K] =Nums[i]; } intTemp =tempsave.size (); if(Tempsave.size () <k) { for(inti = k-1; I >= Temp; --i) tempsave.push_back (Nums[i]); } for(inti =0; I < K; ++i) {nums[i]=Tempsave.back (); Tempsave.pop_back (); } }};
In fact, there are some simpler ways to think about it, such as copying the array once, and then cutting out the part of the array that you need according to the situation.
classSolution { Public: voidRotateintNums[],intNintk) {k= k%N; int* Newnums =New intN2]; for(inti =0; I < n; ++i) {newnums[i]=Nums[i]; Newnums[i+ N] =Nums[i]; } //int res = n-k; for(inti =0; I < n; ++i) {nums[i]= Newnums[i + N-K]; } }};The amount of code is significantly shorter.
Happyleetcode50:rotate Array