Leetcode - 1512. Number of Good Pairs
Leetcode - 1512. Number of Good Pairs
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Solution 1
1
2
3
4
5
6
7
8
9
10
11
12
13
func numIdenticalPairs(nums []int) int {
pairCount := 0
first, second := 0, 1
for first=0; first<len(nums)-1; first++{
for second=1; second<len(nums); second++{
if nums[first]==nums[second] && first<second{
pairCount++
}
}
}
return pairCount
}
Solution 2 (Optimized)
1
2
3
4
5
6
7
8
9
10
11
12
13
func numIdenticalPairs(nums []int) int {
pairCount := 0
mapCount := make(map[int]int)
for _, num := range nums{
mapCount[num]++
// every new occurrence of a number can be paired with every previous occurrence
// so if a number has already appeared 'p' times, we will have 'p-1' new pairs
pairCount = pairCount+(mapCount[num]-1)
}
return pairCount
}
This post is licensed under CC BY 4.0 by the author.