【剑指Offer学习】【面试题38:数字在排序数组中出现的次数】

https://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2?orderByHotValue=1&page=8&onlyReference=false

 

//因为数组中都是整数,所以可以稍微变一下,不是搜索k的两个位置,而是搜索k-0.5和k+0.5

//这两个数应该插入的位置,然后相减即可。

 


int binSearch(int a[],int start,int end,double num) {
    while (start <= end) {
        int half = start + (end -start)/2;
        if (a[half] > num) {
            end = half - 1;
        }
        else if (a[half] < num) {
            start = half + 1;
        }
    }
    return start;
}

int timesOfShown(int a[], int len, int num) {
    if (a == NULL || len == 0) {
        return 0;
    }
    return binSearch(a,0,len-1,num+0.5) - binSearch(a,0,len-1,num-0.5);
}

    int times[] = {1, 2, 2, 2, 2, 2, 2, 8, 9, 10};
    int timesOf = timesOfShown(times,10,2);

 

你可能感兴趣的:(基础知识)