-
题目
题目链接 -
方法一 二分查找
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 5;
int coin[maxn];
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i) {
scanf("%d", &coin[i]);
}
sort(coin, coin + n);
for (int i = 0; i < n - 1; ++i) {
int left = i + 1, right = n;
while (left <= right) {
int mid = (left + right) / 2;
if (coin[mid] == (m - coin[i])) {
printf("%d %d", coin[i], coin[mid]);
return 0;
}
else if (coin[mid] < (m - coin[i])) {
left = mid + 1;
}
else
{
right = mid - 1;
}
}
}
printf("No Solution");
return 0;
}
-
方法二 哈希表
注意遍历时可能出现i与m - i相等的情况,此时必须保证i至少出现两次
#include <cstdio>
#include <memory.h>
const int maxn = 1e3 + 5;
int coin[maxn];
int main()
{
memset(coin, 0, sizeof(coin));
int n, m;
scanf("%d%d", &n, &m);
while (n--) {
int value;
scanf("%d", &value);
coin[value]++;
}
for (int i = 0; i <= m; ++i) {
if (coin[i] && coin[m - i]) {
if (i == (m - i) && coin[i] < 2) // i与m - i相等的情况,此时必须保证i至少出现两次
continue;
printf("%d %d", i, m - i);
return 0;
}
}
printf("No Solution");
return 0;
}