c++中二分查找中的binary_search,lower_bound,upper_bound

注意:如果数组无序,请先用sort将数组排序

binary_search(起始地址,结束地址,要查找的数值)

返回值是 是否存在这么一个数,是一个bool值。

#include<bits/stdc++.h>

using namespace std;

int a[100005];

int main(){
    
    
	int n;
	cin >> n;
	for(int i=0; i<n; i++) {
    
    
		cin >> a[i];
	}
	
	sort(a,a+n);
	cout << binary_search(a,a+n,3); // 查找到为1,查找不到为0

    return 0;
}

lower_bound(起始地址,结束地址,要查找的数值)

返回值就是返回第一次出现大于等于那个要查找的数的地址;

#include<bits/stdc++.h>

using namespace std;

int a[100005];

int main(){
    
    
	int n;
	
	cin >> n;
	
	for(int i=0; i<n; i++) {
    
    
		cin >> a[i];
	}
	
	sort(a,a+n);
	
	cout << lower_bound(a,a+n,3)-a;
	
    return 0;
}

在这里插入图片描述

upper_bound(起始地址,结束地址,要查找的数值)

返回的是被查序列中第一个大于查找的数的指针;

#include<bits/stdc++.h>

using namespace std;

int a[100005];

int main(){
    
    
	int n;
	
	cin >> n;
	
	for(int i=0; i<n; i++) {
    
    
		cin >> a[i];
	}
	
	sort(a,a+n);
	
	cout << upper_bound(a,a+n,3)-a;
	
    return 0;
}

在这里插入图片描述

综合应用

查询某个元素出现的次数

upper_bound - lower_bound

#include<bits/stdc++.h>

using namespace std;

int a[100005];

int main(){
    
    
	int n;
	
	cin >> n;
	
	for(int i=0; i<n; i++) {
    
    
		cin >> a[i];
	}
	
	sort(a,a+n);
	
	cout << upper_bound(a,a+n,3)-lower_bound(a,a+n,3);
	
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44635198/article/details/114375014
今日推荐