Skip to content

Commit 5d80211

Browse files
committed
https://leetcode.cn/problems/count-number-of-bad-pairs/
1 parent f4903fc commit 5d80211

File tree

3 files changed

+26
-11
lines changed

3 files changed

+26
-11
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/count-number-of-bad-pairs/
14+
1315
https://leetcode.cn/problems/number-of-good-pairs
1416

1517
https://leetcode.cn/problems/count-unique-characters-of-all-substrings-of-a-given-string

count-number-of-bad-pairs/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function countBadPairs(nums: number[]): number {
2+
const n = nums.length;
3+
const cnt = new Map<number, number>();
4+
for (const [i, num] of nums.entries()) {
5+
cnt.set(num - i, (cnt.get(num - i) ?? 0) + 1);
6+
}
7+
const ans = Array.from(cnt.values()).reduce(
8+
(a, v) => a + Math.floor((v * (v - 1)) / 2),
9+
0,
10+
);
11+
return Math.floor((n * (n - 1)) / 2) - ans;
12+
}
13+
export default countBadPairs;

number-of-good-pairs/index.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
export default function numIdenticalPairs(nums: number[]): number {
2-
const cnt = new Map<number, number>();
3-
for (const num of nums) {
4-
cnt.set(num, (cnt.get(num) ?? 0) + 1);
5-
}
6-
const ans = Array.from(cnt.values()).reduce(
7-
(a, v) => a + Math.floor((v * (v - 1)) / 2),
8-
0
9-
);
10-
return ans;
11-
}
1+
export default function numIdenticalPairs(nums: number[]): number {
2+
const cnt = new Map<number, number>();
3+
for (const num of nums) {
4+
cnt.set(num, (cnt.get(num) ?? 0) + 1);
5+
}
6+
const ans = Array.from(cnt.values()).reduce(
7+
(a, v) => a + Math.floor((v * (v - 1)) / 2),
8+
0,
9+
);
10+
return ans;
11+
}

0 commit comments

Comments
 (0)