已排序数组中,找出给定数字出现的次数

微软的面试题。。。感觉好高大上的样子
我想的比较简单粗暴

l = [2, 3, 6, 6, 6, 9]
count = 0
for x in l:
    if x == 6:
        count += 1
print(count)

当然对于已排序的数组,无疑二分查找更高效

#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <cstdio>
#define MAX 500010

using namespace std;


int getUpper(int arr[], int left, int right, int key)
{
    while(left < right)
    {
        int mid = (left + right + 1) / 2;
        if (arr[mid] <= key)
            return getUpper(arr, mid, right, key);
        else
            return getUpper(arr, left, mid - 1, key);
    }
    return left;
}

int getLower(int arr[], int left, int right, int key)
{
    while(left < right)
    {
        int mid = (left + right) / 2;
        if (arr[mid] >= key)
            return getLower(arr, left, mid, key);
        else
            return getLower(arr, mid + 1, right, key);
    }
    return right;
}

int main(void)
{
    int a[6] = {2, 3, 6, 6, 6, 9};
    cout << getUpper(a, 0, 5, 6) - getLower(a, 0, 5, 6) + 1 << endl;
    return 0;
}

这里用了两个函数,一个向左找,一个向右找

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值