二分查找模板 low_bound、upper_bound

简介: 二分查找模板 low_bound、upper_bound

下标从1开始,返回长度为n的数组a中最后一个等于key的下标

int search1(int a[], int n, int key){
   
    int l = 1, r = n, ans;
    while (l <= r){
   
        int mid = (l + r) / 2;
        if (a[mid] <= key){
   
            l = mid + 1;
            ans = mid;
        }else{
   
            r = mid - 1;
        }
    }
    return a[ans]==key ? ans : -1;
}

下标从1开始,返回长度为n的数组a中最第一个等于key的下标

int search2(int a[], int n, int key){
   
    int l = 1, r = n, ans;
    while (l <= r){
   
        int mid = (l + r) / 2;
        if (a[mid] < key){
   
            l = mid + 1;
        }else{
   
            r = mid - 1;
            ans = mid;
        }
    }
    return a[ans] == key ? ans, -1;
}

low_bound、upper_bound

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

int main(){
   
    int a[11]={
   0,1,2,3,4,4,4,5,6,7,8};
    //lower_bound(begin, end, key)
    //二从数组的begin位置到end-1位置二分查找第一个大于或等于key的数字,
    //找到返回该数字的地址,不存在则返回end。
    int pos = lower_bound(a+1, a+10+1, 4) - a;
    cout<<pos<<endl;

    //upper_bound(begin, end, key)
    //从数组的begin位置到end-1位置二分查找第一个大于key的数字,
    //找到返回该数字的地址,不存在则返回end。
    int pos2 = upper_bound(a+1, a+10+1, 4) - a;
    cout<<pos2<<endl; 
    return 0;
}
相关文章
|
2月前
|
存储 算法
【洛谷 P1102】A-B 数对 题解(向量+lower_bound+upper_bound)
这是一个编程题目,要求计算给定正整数序列中满足 \( A - B = C \) 的数对个数。输入包含两行:正整数 \( N \) 和 \( C \),以及一串正整数。输出是满足条件的数对数量。使用排序和二分查找优化算法,代码中给出了 AC 解决方案。样例输入为 \( N=4, C=1 \),序列 \( 1, 1, 2, 3 \),输出为 \( 3 \)。数据范围:\( 1 \leq N \leq 2 \times 10^5 \),\( 0 \leq a_i &lt; 2^{30} \),\( 1 \leq C &lt; 2^{30} \)。
19 0
|
机器学习/深度学习
LeetCode-2055 蜡烛之间的盘子 及库函数 lower_bound 和 upper_bound学习使用
LeetCode-2055 蜡烛之间的盘子 及库函数 lower_bound 和 upper_bound学习使用
|
API
LeetCode 374. Guess Number Higher or Lower
我们正在玩一个猜数字游戏。 游戏规则如下: 我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。 每次你猜错了,我会告诉你这个数字是大了还是小了。
66 0
LeetCode 374. Guess Number Higher or Lower
|
API
LeetCode 375. Guess Number Higher or Lower II
我们正在玩一个猜数游戏,游戏规则如下: 我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。 每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。 然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。
96 0
LeetCode 375. Guess Number Higher or Lower II
|
开发工具
15分钟带你了解lower_bound和upper_bound
🍀理解,学会lower_bound和upper_bound原理及其用法
242 0
15分钟带你了解lower_bound和upper_bound
Low Elements--AT
题目描述 Given is a permutation P1,…,PN of 1,…,N. Find the number of integers i (1≤i≤N) that satisfy the following condition: ·For any integer j (1≤j≤i), Pi≤Pj. Constraints ·1≤N≤2×105 ·P1,…,PN is a permutation of 1,…,N. ·All values in input are integers.
95 0
Leetcode-Medium 416. Partition Equal Subset Sum
Leetcode-Medium 416. Partition Equal Subset Sum
111 0
1104. Sum of Number Segments (20) consecutive subsequence 每个数出现的次数
Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence.
955 0