(二分查找)找一对数
Posted lijiahui-123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(二分查找)找一对数相关的知识,希望对你有一定的参考价值。
输入n(n<=100000)个整数,找出其中两个数使之和为m。
题解:
解法一:
int main()
{
int n[100000];
for (int i = 0; i < 100000; i++) {
cin >> n[i];
}
int m;
cin >> m;
sort(n,n+99999);
for (int i = 0; i < 100000; i++) {
int x = m - n[i];
int mid = 50000;
int begin = 0, end = 99999;
while (x != n[mid]&&begin<end) {
if (n[mid] > x) {
end = mid - 1;
}
else {
begin = mid + 1;
}
mid = begin + (end - begin) / 2;
}
if (x == n[mid]) {
cout << n[mid] << "," << n[i] << endl;
break;
}
}
{
int n[100000];
for (int i = 0; i < 100000; i++) {
cin >> n[i];
}
int m;
cin >> m;
sort(n,n+99999);
for (int i = 0; i < 100000; i++) {
int x = m - n[i];
int mid = 50000;
int begin = 0, end = 99999;
while (x != n[mid]&&begin<end) {
if (n[mid] > x) {
end = mid - 1;
}
else {
begin = mid + 1;
}
mid = begin + (end - begin) / 2;
}
if (x == n[mid]) {
cout << n[mid] << "," << n[i] << endl;
break;
}
}
return 0;
}
解法二:
由于排序的复杂度是nlogn所以整个算法的复杂度是nlogn
int s1 = 0, s2 = 100000;
while (n[s1] + n[s2] != m) {
if (n[s1] + n[s2] > m) {
s2--;
}
else {
s1++;
}
}
以上是关于(二分查找)找一对数的主要内容,如果未能解决你的问题,请参考以下文章