给出一个整数K和一个无序数组A,A的元素为N个互不相同的整数,找出数组A中所有和等于K的数对。例如K = 8,数组A:{-1,6,5,3,4,2,9,0,8},所有和等于8的数对包括(-1,9),(0,8),(2,6),(3,5)。
Input
第1行:用空格隔开的2个数,K N,N为A数组的长度。(2 <= N <= 50000,-10^9 <= K <= 10^9)
第2 - N + 1行:A数组的N个元素。(-10^9 <= A[i] <= 10^9)
Output
第1 - M行:每行2个数,要求较小的数在前面,并且这M个数对按照较小的数升序排列。
如果不存在任何一组解则输出:No Solution。
Input示例
8 9
-1
6
5
3
4
2
9
0
8
Output示例
-1 9
0 8
2 6
3 5
这道题超时了好久,双重for循环时间复杂度n2,最后几个数据太大,会超时。应该对for循环进行优化,使用二分查找即可。被坑了好久。
First Try:
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 int main() 5 { 6 long long k, n, n2; 7 cin >> k >> n; 8 long long a[n]; 9 n2 = n; 10 while(n--) { 11 long long x; 12 cin >> x; 13 a[n] = x; 14 } 15 int flag = 0; 16 sort(a, a + n2); 17 for(long long i = 0; i < n2; i ++) { 18 for(long long j = i+1; j < n2; j++) { 19 if(a[i] + a[j] == k) { 20 flag = 1; 21 //cout << a[i] << " " << a[j] << endl; 22 printf("%lld %lld ", a[i], a[j]); 23 j++; 24 continue; 25 } 26 } 27 } 28 if(!flag) { 29 cout << "No Solution" ; 30 } 31 }
Second Try:
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 long long a[50001]; 5 int find(long long n, long long x, long long z) { 6 long long l = z + 1; 7 long long r = n-1; 8 long long m; 9 while(l <= r) { 10 m = (l + r) / 2; 11 //cout << "am=" << a[m] << endl; 12 if(a[m] == x) { 13 // << "m=" << m << endl; 14 return m; 15 } else if(x > a[m]) { 16 l = m + 1; 17 //cout << "am=" << a[m] << endl; 18 } else { 19 r = m - 1; 20 //cout << "am=" << a[m] << endl; 21 } 22 } 23 return false; 24 } 25 int main() 26 { 27 long long k, n, n2; 28 cin >> k >> n; 29 n2 = n; 30 while(n--) { 31 long long x; 32 cin >> x; 33 a[n] = x; 34 } 35 int flag = 0; 36 sort(a, a + n2); 37 for(long long i = 0; i < n2; i++) { 38 int isFind = find(n2, k-a[i], i); 39 if(isFind) { 40 flag = 1; 41 cout << a[i] << " " << a[isFind] << endl; 42 } 43 } 44 if(!flag) { 45 cout << "No Solution"; 46 } 47 48 }