面试题 16.24. 数对和 设计一个算法,找出数组中两数之和为指定值的所有整数对。一个数只能属于一个数对。 示例 1: 输入: nums = [5,6,5], target = 11 输出: [[5,6]] 示例 2: 输入: nums = [5,6,5,6], target = 11 输出: [[5,6],[5,6]] 提示: nums.length <= 100000 方法1:Hash public List<List<Integer>> pairSums(int[] nums, int target) { List<List<Integer>> res = new ArrayList<>(); HashMap<Integer, Integer> map = new HashMap<>(); for (int x : nums) map.put(x, map.getOrDefault(x, 0) + 1); for (int x : nums) { int y = target - x; if (map.containsKey(y) && map.get(y) > 0 && map.containsKey(x) && map.get(x) > 0) { if (x == y && map.get(y) <= 1) continue;//如果x 和 y 相等,则元素的个数至少为2个 map.put(x, map.get(x) - 1); map.put(y, map.get(y) - 1); List<Integer> sub = new ArrayList<>(); res.add(Arrays.asList(x, y)); } } return res; }