-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSolution.cpp
28 lines (25 loc) · 961 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# https://leetcode.com/problems/count-almost-equal-pairs-ii/
class Solution:
def countPairs(self, nums: List[int]) -> int:
d = len(str(max(nums)))
cnt = Counter(nums)
ret = sum(v * (v - 1) // 2 for v in cnt.values())
transform = defaultdict(list)
for x in cnt:
transform[x].append(x)
s = list(str(x).zfill(d))
for i in range(d):
for j in range(i):
if s[i] == s[j]:
continue
s[i], s[j] = s[j], s[i]
y = int("".join(s))
transform[y].append(x)
s[i], s[j] = s[j], s[i]
pairs = set()
for y, xvec in transform.items():
for x1, x2 in combinations(xvec, 2):
pairs.add((min(x1, x2), max(x1, x2)))
for x1, x2 in pairs:
ret += cnt[x1] * cnt[x2]
return ret