简答题
偏难
#7127
找和为K的两个元素 在一个长度为n(n < 1000)的整数序列中,判断是否存在某两个元素之和为k。 时间限制:1000 内存限制:65536 输入 第一行输入…
找和为K的两个元素
在一个长度为n(n < 1000)的整数序列中,判断是否存在某两个元素之和为k。
时间限制:1000
内存限制:65536
输入
第一行输入序列的长度n和k,用空格分开。 第二行输入序列中的n个整数,用空格分开。
输出
如果存在某两个元素的和为k,则输出yes,否则输出no。
样例输入
9 10 1 2 3 4 5 6 7 8 9
样例输出
yes
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">#include <bits/stdc++.h>
using namespace std;
int main() {
int a[1000], n, k, i, j, f = 0;
cin >> n >> k;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (a[i] + a[j] == k)
f = 1;
if (f == 0)
cout << "no";
else
cout << "yes";
return 0;
}</pre><pre class="brush:cpp;toolbar:false">//解法2 数据量比较小暴力即可
#include<bits/stdc++.h>
using namespace std;
int a[1002];
int main(int argc, char *argv[])
{
int n,k;
scanf("%d %d",&n,&k);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
if(a[j]+a[i]==k) {
printf("yes\n");
return 0;
}
printf("no\n");
return 0;
}</pre>
这道题暂未补解析。