To prove safety offer- face questions 53_1- find numbers in the sort array - binary search

/ * 
Title: 
	the number of times a statistical number that appears in the sort array. 
* / 
/ * 
Ideas: 
	1, to traverse from front to back, the time complexity of O (n). 
	2, the digital binary search to the destination target, the forward backward traversal, the time complexity of O (n). 
	3, using dichotomy, recursively find the first position and last position of the number appears, the time complexity of O (logn). 
* / 
#Include <the iostream> 
#include <CString> 
#include <Vector> 
#include <algorithm> 
#include <Map> 


the using namespace STD; 

int getFirstOfK (Vector <int> & A, int Start, End int, int target) { 
    IF (Start> End) return -1; 

    int = MID (Start + End) / 2; 
    IF (A [MID]> target) { 
        return getFirstOfK (A, Start,. 1-MID, target); 
    } the else IF (A [MID] <target) { 
        return getFirstOfK (A, + MID. 1, End, target);
        if(mid == 0 || A[mid-1] != target){
            return mid;
        }else{
            return getFirstOfK(A,start,mid-1,target);
        }
    }
}

int getLastOfK(vector<int> &A,int start,int end,int target){
    if(start > end) return -1;

    int mid = (start+end) / 2;
    if(A[mid] > target){
        return getLastOfK(A,start,mid-1,target);
    }else if(A[mid] < target){
        return getLastOfK(A,mid+1,end,target);
    }else{
        if(mid == end || A[mid+1] != target){
            return mid;
        }else{
            return getLastOfK(A,mid+1,end,target);
        }
    }
}

int getNumbersOfK(vector<int> &A, int target){
    int first = getFirstOfK(A,0,A.size()-1,target);
    int last = getLastOfK(A,0,A.size()-1,target);

    if(last != -1 && first != -1){
        return last - first + 1;
    }
    return 0;

}

int main(){
   vector<int> a = {1,1,3,4,4,4,5};
   cout<<getNumbersOfK(a,1);
}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/12088286.html