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)