[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.
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.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
好数对的数目。
给你一个整数数组 nums 。如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。
返回好数对的数目。
思路一 - 暴力解
暴力解很好想,就是类似于 two sum 一样的两层 for 循环。由于数据量不是很大,这个思路是不超时的。
复杂度
时间O(n^2)
空间O(1)
代码
Java实现
class Solution {
    public int numIdenticalPairs(int[] nums) {
        // corner case
        if (nums == null || nums.length == 0) {
            return 0;
        }
        // normal case
        int res = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    res++;
                }
            }
        }
        return res;
    }
}
思路二 - hashmap
优化的思路是用 hashmap。每遇到一个数字,先去 hashmap 里看他是否存在,如果存在,拿到存在的次数,比如某个数字 X 之前 2 次,那么当我们第 3 次遇到他的时候,就往结果累加 2,因为当前这个 X 可以和之前两次 X 分别配对。
复杂度
时间O(n)
空间O(n)
代码
Java实现
class Solution {
    public int numIdenticalPairs(int[] nums) {
        int res = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int count = map.getOrDefault(num, 0);
            res += count;
            map.put(num, count + 1);
        }
        return res;
    }
}
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号