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

c++ :

//二分查找拓展款 
#include<iostream>
#include<vector>
using namespace std;

 //获取k第一次出现的下标

int getLower(vector<int> data,int k){
        int start = 0,end = data.size()-1;
        int mid = (start + end)/2;       
        while(start <= end){
            if(data[mid] < k){
                start = mid + 1;
            }else{

                end = mid - 1;
            }
            mid = (start + end)/2;
        }
        return start;
 }

//获取k最后一次出现的下标
int getUpper(vector<int> data,int k){
         int start = 0,end = data.size()-1;
        int mid = (start + end)/2;         
        while(start <= end){
            if(data[mid] <= k){
                start = mid + 1;
            }else{
                end = mid - 1;
            }
            mid = (start + end)/2;
        }         
        return end;
}

int GetNumberOfK(vector<int> data ,int k) {
        int lower = getLower(data,k);
        int upper = getUpper(data,k);        
        return upper - lower + 1;
 } 

void main()
{
    int a[15]={1,2,3,4,5,6,7,7,7,7,7,7,7,8,9};
    vector<int> b(a,a+15);
    cout<<GetNumberOfK(b ,7)<<endl;
    while(1);
}

java :

//二分查找拓展款 
public class Overcount {

int findUp(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;
    }

int findDown(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;
}

int findK(int[] a,int k) {
    int c = findDown(a,k) - findUp(a,k) + 1;
    return c;
}

public static void main(String[] args) {
    Overcount aim = new Overcount ();
    int[] a = {1,2,3,4,5,6,7,7,7,7,7,7,7,8,9,10};
    System.out.println(aim.findK(a,7));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值