Given an integer K and an unordered array A, where the elements of A are N different integers, find all pairs in the array A whose sum is equal to K. For example K = 8, array A: {-1,6,5,3,4,2,9,0,8}, all pairs whose sum is equal to 8 include (-1,9), (0,8), (2,6), (3,5).
Input line 1: 2 numbers separated by spaces, KN, N is the length of the A array. (2 <= N <= 50000, -10^9 <= K <= 10^9)
Line 2 - N + 1: N elements of the A array. (-10^9 <= A i i <= 10^9) Output line 1 - M: 2 numbers in each line, the smaller number is required to be in the front, and the M number pairs are arranged in ascending order of the smaller number .
If there is no set of solutions, output: No Solution. Sample Input
8 9 -1 6 5 3 4 2 9 0 8
Sample Output
-1 9 0 8 2 6 3 5
This question, as a chicken, I only figured out more than half of it. Explain that when we do the problem, we must figure out how the data is in the end.
Ideas: 1. There are 2 numbers in each line, the smaller number is required to be in front, and the M number pairs are arranged in ascending order of the smaller number.
If there is no set of solutions, output: No Solution. For Sample Input
, there will be two kinds of problem solving,
1. Store the 2 numbers and the number k, and then sort them.
2. Sort the entire data directly. (sort comes from small to large, note: generally not the functions written by users are the best functions.)
I used the second method from the beginning, so I will not pursue the first method.
General idea: the pointer p is initially 0, and the pointer q is initially N-1;
equal to k, output;
less than k, move p to the right to make the small number larger;
greater than K, move q to the left to make the large number smaller ;
Exit the loop when p >= q.
The ac code is as follows:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int num[50002];
int k,n;
cin>>k>>n;
for(int i=0;i <n;i++)
cin>>num[i];
sort(num,num+n);
bool flag=true;
int i=0;
int j=n-1;
while(1)
{
if(num[i]+num[j]==k)
{
cout<<num[i]<<" "<<num[j]<<endl;
flag=false;
i++;j--;
}
else if(num[i]+num[j]>k)
{
j--;
}
else if(num[i]+num[j]<k)
{
i++;
}
if(i>=j)break;
}
if(flag)cout<<"No Solution"<<endl;
return 0;
}