[CareerCup][Google Interview] 找出现次数

本文介绍了如何通过修改二分查找算法,在已排序的数组中找到目标元素出现的最左位置和最右位置,从而计算出目标元素的出现次数,实现了O(log n)的时间复杂度。

Given a sorted array and a number n.How can u find the number of occurance of n in the array . should be o(logn)

http://www.careercup.com/question?id=8877058

改变一下二分查找的方法,一次找到最左边,另一次找到最右边。

#include <iostream>
#include <vector>
using namespace std;

int findPos(vector<int> &a, int left, int right, int key, bool findLeft)
{
    if (left > right)
        return -1;

    int mid = (left + right) / 2;

    if (a[mid] == key)
    {
        int pos = findLeft ? findPos(a, left, mid - 1, key, findLeft) : findPos(a, mid + 1, right, key, findLeft);
        return (pos == -1 ? mid : pos);
    }
    else if (a[mid] > key)
    {
        return findPos(a, left, mid - 1, key, findLeft);
    }
    else
    {
        return findPos(a, mid + 1, right, key, findLeft);
    }
}

int main()
{
    vector<int> a;
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 5; j++)
            a.push_back(i);

    int pos1 = findPos(a, 0, a.size() - 1, 5, true);
    int pos2 = findPos(a, 0, a.size() - 1, 5, false);

    cout << pos1 << ' ' << pos2 << endl;
}

转载于:https://www.cnblogs.com/chkkch/archive/2012/10/29/2744640.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值