Moving an array to the right to move K bits requires time complexity O (n)

Source: Internet
Author: User

Tonight did a company's network pen test, long time no brush problem, now slag to die, inside Youdao Program design problem is to put an array to the right of the circular move K-bit requirements time complexity O (n) to the method defined as

 Public void solution (int a[],int length,int k)

I thought it was easy, the results of a write to find only one bit ...

 Public void solution (int []a,int length,int  k) {    int temp=a[ Length-1];      for (int j=length-1;j>0;j--) {        a[j]=a[j-1];    }    a[0]=temp;}

And then found that adding a loop can not move the K-bit? But the complexity of the time is O (k*n). The last O (n) algorithm has a problem there is no time to use this.

 Public void Solution (int []a,int length,int  k) {    for (int i=0;i<k;i++) {             int temp=a[length-1];//The last one here is wrong.          for (int j=length-1;j>0;j--) {            a[j]=a[j-1];        }            a[0]=temp;}    }   

Just suddenly remembered, can actually direct the first number to the right to move the K-bit, the second is followed by the first number, the third followed by the second is not OK?

#include <iostream.h>voidConvertintA[],intStartintend) {    intk, temp;  for(k =0; K < (end-start+1)/2; k++) {Temp= a[start+K]; A[start+k] = a[end-K]; A[end-K] =temp; }} voidYiwei (intA[],intNintk) {CONVERT (A,0, K-1);//first, the number of k in the array before the inverse (0~k-1),Convert (a,k,n-1);//first, the number of n-k after the array is reversed (k~n-1),Convert (A,0, N-1);//first, the entire array is reversed,} voidMain () {inta[6] = {1,2,3,4,5,6}; Yiwei (A,6,2);  for(inti =0; I <6; i++) cout<< A[i] <<'\ t';}

Moving an array to the right to move K bits requires time complexity O (n)

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.