• 统计一个数字在排序数组中出现的次数(二分法)





    #include<iostream>
    #include<algorithm>
    #include<stdio.h>
    using namespace std;
    int a[500001];
    int binarySearchFirstPos(int l, int r, int key)
    {
    	int mid;
        while(l<=r){
    	mid =(l+r)/2;
    	if(a[mid]<key)
    		l=mid+1;
    	else if(a[mid]>key)
    		r=mid-1;
    	else {
    	if(mid==l||a[mid-1]!=key)
    		return mid;
    	else r=mid-1;
    	}
    	}
    	return -1;
    }
    int binarySearchLastPos(int l, int r, int key)
    {
    	int mid;
        while(l<=r){
    	mid =(l+r)/2;
    	if(a[mid]<key)
    		l=mid+1;
    	else if(a[mid]>key)
    		r=mid-1;
    	else {
    	if(mid==r||a[mid+1]!=key)
    		return mid;
    	else l=mid+1;
    	}
    	}
    	return -1;
    }
    int numOfKey(int l,int r, int key)
    {
        int firstPos = binarySearchFirstPos(l,r, key);
        int lastPos = binarySearchLastPos(l,r, key);
        
        if(firstPos == -1)
            return 0;
        else
            return lastPos - firstPos + 1;
    }
    int main(){
    	int n,m,i;
    	scanf("%d%d",&n,&m);
    	for(i=1;i<=n;i++)
    		scanf("%d",&a[i]);
    	sort(a+1,a+n+1);
    	int tem;
    	for(i=1;i<=m;i++)
    	{
    		scanf("%d",&tem);
    		cout<<numOfKey(1,n,tem)<<endl;
    	}
    
    }


    版权声明:本文为博主原创文章,未经博主允许不得转载。

    today lazy . tomorrow die .
  • 相关阅读:
    Codeforces Round #239(Div. 2) 做后扯淡玩
    hdu 3507 Print Article
    prufer序列
    POJ 2778 DNA Sequence
    Codeforces Round #237 (Div. 2)
    poj3352
    图论知识
    POJ 2186
    Codeforces Round #236 (Div. 2)
    POJ 2823 Sliding Window
  • 原文地址:https://www.cnblogs.com/france/p/4808644.html
Copyright © 2020-2023  润新知