数字在排序数组中出现的次数

题目:统计一个数字在排序数组中出现的次数。例如,输入排序数组{1,2,3,3,3,3,4,5}和数字3由于3在这个数组中出现了4次,因此输出4。

 

#include <iostream>
using namespace std;

int getfirstk(int *a,int k,int low,int high)
{
    if(low>high)
        return -1;
    int mid=(low+high)/2;
    if(a[mid]==k)
    {
        if((mid>0&&a[mid-1]!=k)||mid==0)
            return mid;
        else
            high=mid-1;
    }
    else if(a[mid]>k)
        high=mid-1;
    else
        low=mid+1;
    return getfirstk(a,k,low,high);
}

int getlastk(int *a,int k,int low,int high)
{
    if(low>high)
        return -1;
    int mid=(low+high)/2;
    if(a[mid]==k)
    {
        if((mid!=high&&a[mid+1]>k)||mid==high)
            return mid;
        else
            low=mid+1;
    }
    else if(a[mid]>k)
        high=mid-1;
    else
        low=mid+1;
    return getlastk(a,k,low,high);
}

int main()
{
    int a[]={1,2,3,3,3,3,4,5};
    int first,last,x,k;
    cin>>k;
    int low=0,high=sizeof(a)/sizeof(a[0])-1;//high=8-1;
    first=getfirstk(a,k,low,high);
    last=getlastk(a,k,low,high);
    if(first!=-1&&last!=-1)
    {
        x=last-first+1;
        cout<<x;
    }
}

 

posted @ 2017-05-01 09:20  home普通的人  阅读(139)  评论(0编辑  收藏  举报