Q: To move an array of N elements to the right by the K-bit, requiring a time complexity of O (N), and only two additional variables are allowed.
The beginning of the idea:
1. If k= integer times n, complete; k greater than n,k=n%k;k less than n, start processing.
2.tmp1 save removed Element a[k];a[0] put in K;TMP2 save a[2k], Tmp1 put 2K;TMP1 save a[3k],tmp2 put into 3k ... Until the position [0] is placed into a new value, a round cycle is complete. This is a solitaire game that starts from position [0] and returns to position [0].
After careful consideration, it is found that, if n%k==0, you need to start [0], [0] end ... To [k-1] start [k-1] end, all executed again. If n%k! =0, it may be executed at one time, or it may run out of the 0~k-1 part,
So this method also needs to record from [0] to [k-1] which has been successfully reset the new elements, all back to the completion.
This method seems to be not very concise, the code is as follows:
Then there is a new method, with the reverse array: The whole process of dividing the array into 0~n-k-1 and n-k~n-1 two parts, then flip to the left, flip the right, and then the overall flip, there is the final loop right shift K effect.
With I in the left range, the n-k+i in the right range have been tried, and indeed finally moved to I+k, I, meet the conditions
//reverse the elements between start and end in buffervoidReverse (intBuffer[],intStartintend) { while(Start <end) { inttemp =buffer[start]; buffer[Start++ ] =buffer[end]; buffer[End-- ] =temp; }}//moves the array with n elements to the right of the K-bitvoidShift (intBuffer[],intNintk) {k%=N; Reverse (Buffer,0, N-k-1) ; Reverse (buffer, n-K, N-1 ) ; Reverse (Buffer,0N1 ) ;}
Array Loop right