统计一个数字在排序数组中出现的次数。

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

//方案一

public class Solution {

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;
}

}

//方案二

public class Solution {

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;
}

}

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看