标签:while nlogn war nlog out i++ == include clu
输入n(n<=100000)个整数,找出其中两个数使之和为m。
题解:
解法一:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
using namespace std;
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;
}
}
return 0;
}
解法二:
由于排序的复杂度是nlogn所以整个算法的复杂度是nlogn
int s1 = 0, s2 = 100000;
while (n[s1] + n[s2] != m) {
if (n[s1] + n[s2] > m) {
s2--;
}
else {
s1++;
}
}
(二分查找)找一对数
标签:while nlogn war nlog out i++ == include clu
原文地址:https://www.cnblogs.com/lijiahui-123/p/12353214.html