AlgoMaster Logo

Number of Good Pairs

nums=[1, 2, 3, 1, 1, 3]
1class Solution {
2    public int numIdenticalPairs(int[] nums) {
3        HashMap<Integer, Integer> map = new HashMap<>();
4        int count = 0;
5
6        for (int num : nums) {
7            if (map.containsKey(num)) {
8                // Increment count by occurrences seen so far
9                count += map.get(num);
10                // Increment occurrence count in map
11                map.put(num, map.get(num) + 1);
12            } else {
13                // First occurrence, add to map
14                map.put(num, 1);
15            }
16        }
17        return count;
18    }
19}
0 / 17
123113012345Hash Mapcount = 0