数对和

设计一个算法,找出数组中两数之和为指定值的所有整数对。一个数只能属于一个数对。

  • 输入: nums = [5,6,5], target = 11
    输出: [[5,6]]

  • 输入: nums = [5,6,5,6], target = 11
    输出: [[5,6],[5,6]]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var pairSums = function(nums, target) {
const n = nums.length;
const used = new Int32Array(n);
const map = new Map();
const result = [];
nums.forEach((num, index) => {
const extra = target - num;
if(map.has(extra) && map.get(extra) > 0) {
const count = map.get(extra) || 0
map.set(extra, count - 1);
result.push([num,extra]);
} else {
const count = map.get(num) || 0;
map.set(num,count + 1)
}
});
return result;
};