↓快轉到主要內容
  1. LeetCode/

LeetCode 1512: Number of Good Pairs

·1 分鐘· ·
LeetCode Easy Math Hash-Table Counting Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-12-18

  • 提交紀錄:Accepted ×2(Python)→ Compile Error → Accepted ×2(C++)

解題思路
#

nums[i] == nums[j] 而且 i < j 的配對數。

  • 暴力:兩層迴圈 O(n^2),n <= 100 也能過。
  • 計數:每種數出現 c 次,配對數是 c × (c - 1) / 2。
  • 邊掃邊數:讀到 x 時,它可以跟前面每個 x 配一對,所以答案加上 cnt[x],再把 cnt[x] 加 1。

我的解法
#

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        cnt = Counter()
        pairs = 0
        for x in nums:
            pairs += cnt[x]                        # 跟前面每個 x 配一對
            cnt[x] += 1
        return pairs

我先用 Python 寫了暴力和組合數兩種,再用 C++ 練習邊掃邊數的寫法;C++ 那次的 Compile Error 是 return res 少了分號。

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 組合數用 / 會變成浮點數,用 //,或直接邊掃邊數。

面試口說整理
#

我邊掃邊數:讀到一個數時,它可以跟前面每個相同的數配成一對,所以答案加上目前它出現過的次數,再把次數加一。時間 O(n)。

相關文章

LeetCode 914: X of a Kind in a Deck of Cards
·1 分鐘
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 解題筆記:每種卡片的張數都要能被同一個 X >= 2 整除,也就是所有張數的 GCD >= 2
LeetCode 3712: Sum of Elements With Frequency Divisible by K
·1 分鐘
LeetCode Easy Hash-Table Counting Array
LeetCode 3712 解題筆記:先數每個值的次數,次數能被 k 整除的就加上「值 × 次數」
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 1814: Count Nice Pairs in an Array
·1 分鐘
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 解題筆記:把條件移項成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),按這個值分組數 pair,記得取模
LeetCode 1128: Number of Equivalent Domino Pairs
·1 分鐘
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 解題筆記:把每張骨牌正規化成 (小, 大) 當 key 計數,每個 key 有 c 張就有 c(c - 1) / 2 對
LeetCode 819: Most Common Word
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 解題筆記:標點換成空白、全部轉小寫再切單字,計數後找出不在 banned 裡的最多的那個