1. 程式人生 > 實用技巧 >LeetCode1512-好數對的數目

LeetCode1512-好數對的數目

非商業,LeetCode連結附上:

https://leetcode-cn.com/problems/number-of-good-pairs/

進入正題。

題目:

給你一個整數陣列 nums 。

如果一組數字 (i,j) 滿足 nums[i] == nums[j] 且 i < j ,就可以認為這是一組 好數對 。

返回好數對的數目。

示例:

示例 1:

輸入:nums = [1,2,3,1,1,3]
輸出:4
解釋:有 4 組好數對,分別是 (0,3), (0,4), (3,4), (2,5) ,下標從 0 開始
示例 2:

輸入:nums = [1,1,1,1]
輸出:6
解釋:陣列中的每組數字都是好數對
示例 3:

輸入:nums = [1,2,3]
輸出:0

提示:

1 <= nums.length <= 100
1 <= nums[i] <= 100

程式碼實現:

//方法一 暴力法
public static int numIdenticalPairs(int[] nums) {

        int count = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    count++;
                }
            }
        }

        return count;
}
//時間複雜度O(n^2),空間複雜度O(1)

//方法二 雜湊表統計+組合計數
public int numIdenticalPairs(int[] nums) {

        Map<Integer, Integer> m = new HashMap<>();
        for(int num : nums) {
            m.put(num, m.getOrDefault(num, 0) + 1);
        }
        
        int ans = 0;
        for(Map.Entry<Integer, Integer> entry : m.entrySet()) {
            int v = entry.getValue();
            ans += v * (v - 1) / 2;
        }
        
        return ans;

}
//時間複雜度O(n),空間複雜度O(n)

//方法三 利用陣列性質+提示條件
public int numIdenticalPairs(int[] nums) {

        int ans = 0;
        int[] temp = new int[100];

        for(int num : nums) {
            ans += temp[num - 1];
            temp[num - 1]++;
        }

        return ans;

}
//時間複雜度O(n),空間複雜度O(n)

分析:

三種方法,三種思維。

附註:

第三種詳解:https://leetcode-cn.com/problems/number-of-good-pairs/solution/zhe-gu-ji-shi-wo-xie-zen-yao-duo-ti-yi-lai-zui-dua/

--End