[LeetCode]#1512. Number of Good Pairs
1 min readJul 13, 2020
Environment: Python 3.7
Key technique: {}
Given an array of integers nums
.
A pair (i,j)
is called good if nums[i]
== nums[j]
and i
< j
.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Analysis:
- Find number showing frequency in nums.
- Use formula n(n-1)/2 to calculate pairs.
- Return all pair result.
Solution:
class Solution:
def numIdenticalPairs(self, nums):
f={}
ans=0
for num in nums:
if not num in f:
f[num]=0
f[num]+=1
for num in f:
n=f[num]
ans+=(n*(n-1)//2)
return ans
Submissions:
Reference: