题目链接
求解过程 : 首先对数组从大到小排列 , 从头到尾处理数组的每一个元素,复杂度是O(n),把求解目标和(target)的过程当成
a
r
r
[
a
]
+
a
r
r
[
b
]
=
t
a
r
g
e
t
arr[a]+arr[b]=target
arr[a]+arr[b]=target
也就是
a
r
r
[
a
]
=
t
a
r
g
e
t
−
a
r
r
[
b
]
arr[a]=target-arr[b]
arr[a]=target−arr[b]
的过程
我们遍历数组,将每一个元素作为被减的元素arr[b],然后二分查找arr[a],二分查找的值必定比arr[b]大,所以二分查找总是从索引b+1开始的
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 1;
int arr[N];
int findValue(int arr[] , int arrlen , int target,int start)
{
int left = start , right = arrlen - 1;
while(left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] > target)
{
right = mid - 1;
}else if (arr[mid] < target)
{
left = mid + 1;
}else {
return mid;
}
}
return -1;
}
int main()
{
// arr[a] + arr[b] = N --> arr[a] = N - arr[b]
int arrlen , querry ,flag = 0;
cin >> arrlen >> querry ;
for (int i = 0 ; i < arrlen ; i++)
{
cin >> arr[i];
}
sort(arr,arr + arrlen);
while (querry--)
{
int target ;
cin >> target ;
flag = 0;
for (int i = 0 ; i < arrlen ; i++)
{
int temp = target - arr[i];
int returnValue = findValue(arr, arrlen, temp,i+1);
if (returnValue != -1)
{
cout << 1 << '\n';
flag = 1;
break;
}
}
if (flag == 0)
{
cout << 0 << '\n';
}
}
return 0;
}