Leetcode 1814. Count Nice Pairs in an Array

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count Nice Pairs in an Array

2. Solution

解析:Version 1,由题目可知nums[i] - rev(nums[i])相等的两个数即可构成一个合适的对,因此统计nums[i] - rev(nums[i])相等的数值即可。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def countNicePairs(self, nums: List[int]) -> int:
count = 0
n = len(nums)
stat = {}
MODULE = 10**9 + 7
for i in range(n):
diff = nums[i] - int(str(nums[i])[::-1])
stat[diff] = stat.get(diff, 0) + 1
if stat[diff] > 1:
count += stat[diff] - 1
return count % MODULE

Reference

  1. https://leetcode.com/problems/count-nice-pairs-in-an-array/
如果有收获,可以请我喝杯咖啡!