手撕代码 无序整数集合N,找两个数相加等于100?
1 个回答
勇敢一点吧!我们不会比今年更年轻了。萧薰儿# 方法一:HashSet(找任意一对 / 找全部唯一对) * 时间 O(n),空间 O(n) ```java import java.util.*; public class TwoSum100 { // 找“任意一对”,无则返回 null public static int[] findAnyPair(int[] a) { if (a == null || a.length < 2) return null; Set<Integer> seen = new HashSet<>(a.length * 2); for (int x : a) { int y = 100 - x; if (seen.contains(y)) return new int[]{x, y}; seen.add(x); } return null; } // 找“全部唯一对”,每对只给一次,例如 (40,60) 不重复 public static List<int[]> findAllPairs(int[] a) { List<int[]> res = new ArrayList<>(); if (a == null || a.length < 2) return res; Map<Integer, Integer> cnt = new HashMap<>(); for (int x : a) cnt.merge(x, 1, Integer::sum); Set<Integer> used = new HashSet<>(); for (int x : cnt.keySet()) { int y = 100 - x; if (used.contains(x)) continue; if (x == y) { if (cnt.get(x) >= 2) res.add(new int[]{x, y}); } else if (cnt.containsKey(y)) { res.add(x < y ? new int[]{x, y} : new int[]{y, x}); } used.add(x); used.add(y); } // 按小到大排序更直观(可选) res.sort(Comparator.comparingInt(p -> p[0])); return res; } } ``` # 方法二:排序 + 双指针(找全部唯一对) * 时间 O(n log n),空间 O(1) 额外(就地排序) ```java import java.util.*; public class TwoSum100TwoPointers { public static List<int[]> findAllPairs(int[] a) { List<int[]> res = new ArrayList<>(); if (a == null || a.length < 2) return res; Arrays.sort(a); int i = 0, j = a.length - 1; while (i < j) { long sum = (long)a[i] + a[j]; // 泛化时避免溢出 if (sum == 100) { res.add(new int[]{a[i], a[j]}); int li = a[i], rj = a[j]; while (i < j && a[i] == li) i++; // 去重 while (i < j && a[j] == rj) j--; } else if (sum < 100) { i++; } else { j--; } } return res; } } ``` # 选型建议 * **只需判断/拿一对**:用 HashSet 的 `findAnyPair`,最快最简。 * **要列出所有唯一解**:数据量很大且内存吃紧→排序双指针;内存够→HashMap 计数更直观。 * 注意特殊对 `(50,50)`:需要至少两个 `50` 才算一对,上面两种实现都已正确处理。发布于 2025-08-19 16:00 •IP属地 内蒙古举报评论收藏
公众号进入网站体验更佳

