0%

LeetCode 1512. Number of Good Pairs

題目

1
2
3
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

解法思維

想到跑雙迴圈判斷

1
2
3
4
5
6
7
8
9
10
11
12
var numIdenticalPairs = function(nums) {
let counter = 0;
for (let i = 0; i < nums.length; i++) {
for (let j = i+1; j < nums.length; j++) {
if(nums[i]===nums[j]){
counter++
}

}
}
return counter
};

利用for of

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var numIdenticalPairs = function(nums) {
let obj = {};
let counter = 0;

for (val of nums) {
if (obj[val]) {
counter += obj[val];
obj[val]++;
} else {
obj[val] = 1;
}
}
console.log(obj);
return counter;
};

JS-for…in與for…of的差別