統計一個數字在排序數組中出現的次數。

//方案一code

public class Solution {io

public int GetNumberOfK(int [] array , int k) {


    return two(array,k+0.5)-two(array,k-0.5);
   
}

public int two(int a[],double k){
   int low = 0;
   int end = a.length-1;
    
   int mid;
    
   while(low<=end){
       mid = (end-low)/2+low;
       
       if(a[mid]<k)
           low=mid+1;
       else if(a[mid]>k)
           end=mid-1;
   }
    
    return low;
}

}class

//方案二while

public class Solution {co

public int GetNumberOfK(int [] array , int k) {

  return f1(array,k)-f(array,k)+1;
   
}

public int f(int a[],int k){
    int start=0;
    int end = a.length-1;
    
    int mid = (start+end)/2;
    
    while(start<=end){
       if(a[mid]<k)
           start=mid+1;
       else
           end=mid-1;
        
        mid = (start+end)/2;
    }
    return start;
}

public int f1(int a[],int k){

    int start=0;
    int end = a.length-1;
    
    int mid = (start+end)/2;
    
    while(start<=end){
       if(a[mid]<=k)
           start=mid+1;
       else
           end=mid-1;
        
        mid = (start+end)/2;
    }
    return end;
}

}return

相關文章
相關標籤/搜索