Array Loop Right Shift

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.