方法一 暴力循环
var numIdenticalPairs = function(nums) {
let ans = 0;
for (let i = 0; i < nums.length; ++i) {
for (let j = i + 1; j < nums.length; ++j) {
if (nums[i] == nums[j]) {
++ans;
}
}
}
return ans;
};
消耗时间和内存情况:
方法二:组合计数
var numIdenticalPairs = function(nums) {
let m=new Map();
for (let num of nums) {
m.set(num,m.get(num)+1 || 1)
}
let ans = 0;
for (const [k,v] of m) {
ans += v * (v - 1) / 2;
}
return ans;
};
消耗时间和内存情况: