1、知识点
(1)查找最接近的数,可用lower_bound,需要考虑最左、最右、中间,三种情况
(2)查找范围,可用lower_bound和upper_bound,取q-p的差值
(3)存在相同的数,可用lower_bound和upper_bound
2、例题:#11664. 三角形数
//思路:计算每个三角形数,放在t数组中,在t数组中二分查找x-t[i]。
int t[50002];
int main()
{
int x;
cin>>x;
for(int i=1; i<=50000; i++) //计算每个三角形数
{
t[i]=i*(i+1)/2;
}
for(int i=1; i<=50000; i++)
{
int p=lower_bound(t+1,t+50001,x-t[i])-t; //二分查找x-t[i]
if(p<50001&&t[p]==x-t[i])
{
cout<<"YES";
return 0;
}
}
cout<<"NO";
return 0;
}