Skip to content

Commit 1719e40

Browse files
committed
1814. 统计一个数组中好对子的数目
1 parent e3d0641 commit 1719e40

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@
175175
|1780|[判断一个数字是否可以表示成三的幂的和](https://leetcode.cn/problems/check-if-number-is-a-sum-of-powers-of-three/)|[JavaScript](./algorithms/check-if-number-is-a-sum-of-powers-of-three.js)|Medium|
176176
|1807|[替换字符串中的括号内容](https://leetcode.cn/problems/evaluate-the-bracket-pairs-of-a-string/)|[JavaScript](./algorithms/evaluate-the-bracket-pairs-of-a-string.js)|Medium|
177177
|1813|[句子相似性 III](https://leetcode.cn/problems/sentence-similarity-iii/)|[JavaScript](./algorithms/sentence-similarity-iii.js)|Medium|
178+
|1814|[统计一个数组中好对子的数目](https://leetcode.cn/problems/count-nice-pairs-in-an-array/)|[JavaScript](./algorithms/count-nice-pairs-in-an-array.js)|Medium|
178179
|1832|[判断句子是否为全字母句](https://leetcode.cn/problems/check-if-the-sentence-is-pangram/)|[JavaScript](./algorithms/check-if-the-sentence-is-pangram.js)|Easy|
179180
|1945|[字符串转化后的各位数字之和](https://leetcode.cn/problems/sum-of-digits-of-string-after-convert/)|[JavaScript](./algorithms/sum-of-digits-of-string-after-convert.js)|Easy|
180181
|2032|[至少在两个数组中出现的值](https://leetcode.cn/problems/two-out-of-three/)|[JavaScript](./algorithms/two-out-of-three.js)|Easy|
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 1814. 统计一个数组中好对子的数目
3+
* @param {number[]} nums
4+
* @return {number}
5+
*/
6+
var countNicePairs = function (nums) {
7+
const rev = (num) => {
8+
let result = 0;
9+
while (num) {
10+
result = result * 10 + (num % 10);
11+
num = Math.floor(num / 10);
12+
}
13+
return result;
14+
};
15+
16+
// nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
17+
// <=> 等价于
18+
// nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])
19+
20+
// 主要思路 (by 评论区大佬):
21+
// 假设:以 nums[i] - rev(nums[i]) 为整体出现的次数为N,之后假想将这 N 个数放入一个数组中 L
22+
// 则: `好的` 就相当于这个数组 L 的所有长度为 2 的子集,而所求个数即为符合条件的子集个数
23+
// 易知:长度为 N 的数组 L,其长度为 2 的子集个数为 N * (N - 1) / 2
24+
25+
let result = 0;
26+
const mod = 1e9 + 7;
27+
const map = {};
28+
29+
// 0 + 1 + 2 + ... + (n - 1)
30+
// =>
31+
// Sum = n * (n - 1) / 2
32+
33+
for (let i = 0; i < nums.length; i++) {
34+
const key = nums[i] - rev(nums[i]);
35+
result = (result + (map[key] || 0)) % mod;
36+
map[key] = (map[key] || 0) + 1;
37+
}
38+
return result;
39+
};

0 commit comments

Comments
 (0)