Ideas:
Should be used to find the first and last occurrence of the number of two points, subtract. O (LOGN)
intFindleft (intA[],intNintnum) { intL =0, R = N-1; while(L <=r) {intm = L + (r-l)/2; if(a[m] = = num)//The difference between the common binary search equals here { if(M = =0|| A[m-1]! = num)//If this is the first number or the number in front of it is not Num then this position is where the first num appears. returnm; Else //otherwise num in the left halfr = M-1; } Else if(A[m] <num) {L= m +1; } Else{R= M-1; } } return-1;//didn't find}intFindright (intA[],intNintnum) { intL =0, R = N-1; while(L <=r) {intm = L + (r-l)/2; if(A[m] = =num) { if(M = = N-1|| A[m +1]! = num)////If this is the last number or the number behind it is not Num then this position is where the last num appears. returnm; Else //otherwise the last num in the right halfL = m +1; } Else if(A[m] <num) {L= m +1; } Else{R= M-1; } } return-1;//didn't find}intTimesintA[],intNintnum) { if(A = = NULL)return 0; intL =Findleft (A, n, num); intR =Findright (A, n, num); return(L = =-1|| r = =-1) ?0: R-l +1;}intMain () {inta[Ten] = {1,2,3,3,3,3,4,5}; intAns = times (A,8,5); return 0;}
The first thing to write is to use normal binary search to find a specified number and then expand Around, O (N) is not good.
//O (N) solution is not goodintAppeartimes (intA[],intNintnum) { intL =0; intr = N-1; intpos =-1;//The subscript for the found Num while(L <= R)//Two-point lookup to find a num { intm = L + (r-l)/2; if(A[m] = =num) {POS=m; Break; } Else if(A[m] <num) L= m +1; ElseR= M-1; } if(pos = =-1)//no such number return 0; L= R =POS; while(L >=0&& a[l] = = num)//find the left borderl--; while(R < n && a[r] = = num)//find the right borderr++; returnR-l-1;}
"Sword Point offer" topic 38 number of occurrences in a sorted array