2364. 统计坏数对的数目
为保证权益,题目请参考 2364. 统计坏数对的数目(From LeetCode).
解决方案1
Python
python
from typing import List
# class Solution:
# def countBadPairs(self, nums: List[int]) -> int:
#
# ans = 0
# for i in range(len(nums)):
# for j in range(i + 1, len(nums)):
# if nums[j] - nums[i] != j - i:
# ans += 1
# return ans
class Solution:
def countBadPairs(self, nums: List[int]) -> int:
for i in range(len(nums)):
nums[i] = nums[i] - i
ans = 0
d = dict()
for i in range(len(nums)):
if nums[i] in d:
ans += i - d[nums[i]]
d[nums[i]] += 1
else:
ans += i
d[nums[i]] = 1
return ans
if __name__ == "__main__":
so = Solution()
print(so.countBadPairs([4, 1, 3, 3]))
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
29
30
31
32
33
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
29
30
31
32
33