C++ &算法基础【day01-02】

#include 
#include 
using namespace std;

/*
二分查找->分界查找
统计⼀个数字在排序数组中出现的次数。
数组是有序的!
*/
int left_bound(vector<int> &nums, int target)
{
    int left = 0;
    int right = nums.size() - 1;
    // 搜索区间为[left, right]
    while (left <= right)
    {
        int mid = left + (right - left) / 2;
        if (nums[mid] < target)
        {
            // 搜索区间变为 [mid+1, right]
            left = mid + 1;
        }
        else if (nums[mid] > target)
        {
            // 搜索区间变为 [left, mid-1]
            right = mid - 1;
        }
        else
        {
            // 收缩右边
            right = mid - 1;
        }
    }
    // 边界判定
    if (left >= nums.size() || nums[left] != target)
    {
        return -1;
    }
    return left;
}

int right_bound(vector<int> &nums, int target)
{
    int left = 0;
    int right = nums.size() - 1;
    // 搜索区间为[left, right]
    while (left <= right)
    {
        int mid = left + (right - left) / 2;
        if (nums[mid] < target)
        {
            // 搜索区间变为 [mid+1, right]
            left = mid + 1;
        }
        else if (nums[mid] > target)
        {
            // 搜索区间变为 [left, mid-1]
            right = mid - 1;
        }
        else
        {
            // 收缩左边
            left = mid + 1;
        }
    }
    // 边界判定
    if (right < 0 || nums[right] != target)
    {
        return -1;
    }
    return right;
}

int serach(vector<int> &nums, int target)
{
    int left_index = left_bound(nums, target);
    if (left_index == -1)
    {
        return 0;
    }
    int right_index = right_bound(nums, target);
    // 根据左右边界即可推导出元素出现的次数
    cout << right_index << " " << left_index << endl;
    return right_index - left_index + 1;
}

int main()
{
    vector<int> nums{5, 7, 8, 8, 8, 10};
    int target = 8;
    cout << "输出结果为:" << serach(nums, target) << endl;
    return 0;
}

你可能感兴趣的:(算法,c++,数据结构)