排序后首尾双指针夹逼两数之和:和偏小放弃整行、和偏大放弃整列,首次命中天然就是题面要求的较小数最小的数对。
OJ: roj
题目 ID: 1244
难度:入门
标签:入门排序双指针python
创建: 2026-09-30 01:22
更新: 2026-10-05 06:30
题目描述
给出 No。
输入第一行 4、2 5 1 4、6;对应输出 1 5。
思路
把数列升序排序,用首尾双指针
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-30 01:23
# update_at: 2026-09-30 01:23
import sys
def find_pair(nums: list[int], target: int) -> tuple[int, int] | None:
"""双指针求和为 target 的数对:首个命中即"较小的数更小"的最优解。"""
i, j = 0, len(nums) - 1
while i < j:
total = nums[i] + nums[j]
if total < target:
i += 1 # 左端已最小,j 及其左侧都配不出 target,放弃 nums[i]
elif total > target:
j -= 1 # 同理放弃 nums[j]
else:
return nums[i], nums[j]
return None
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data)
nums = sorted(next(data) for _ in range(n)) # 排序后双指针才能单调移动
target = next(data)
pair = find_pair(nums, target)
print("No" if pair is None else f"{pair[0]} {pair[1]}")
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 06:30
* update_at: 2026-10-05 06:30
*/
#include <algorithm>
#include <cstdio>
using namespace std;
typedef long long ll;
const int MAXN = 100005;
ll a[MAXN]; // a[1..n] 存放输入的 n 个整数,排序后升序
int main() {
ll n, m;
scanf("%lld", &n);
for (ll i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
}
scanf("%lld", &m);
// 升序排序后,和偏小就放弃左端,和偏大就放弃右端,
// 行按左端点从小到大访问,首次命中即"较小的数更小"的最优数对。
sort(a + 1, a + n + 1);
ll i = 1;
ll j = n;
while (i < j) {
ll sum = a[i] + a[j];
if (sum < m) {
i++; // a[i] 与任何右侧元素都配不出 m,整行放弃
} else if (sum > m) {
j--; // 同理整列放弃
} else {
printf("%lld %lld\n", a[i], a[j]);
return 0;
}
}
printf("No\n");
return 0;
}