日野弥生:勉強しよう

LeetCode 1512 - 好数对的数目

发表于2025年02月03日

#数组 #哈希表 #数学 #计数

由于不同的索引相同的值就能构成一个数对,所以用组合数公式对结果进行求解。那么就应该先把不同数字出现的频次进行统计,利用python3中的字典或者C++中的std::map即可进行处理。

相同的数中,任意挑选两个即可构成数对,即$C_n^2$。

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        # 初始化字典用花括号
        resultDict = {}
        for num in nums:
            if num in resultDict:
                resultDict[num] = resultDict[num] + 1
            else:
                resultDict[num] = 1
        result = 0
        # 注意for循环中的元素是key
        for key in resultDict:
            # get函数拿到value
            value = resultDict.get(key)

            # 利用math模块的组合数函数方法直接获取组合数的值
            result += math.comb(value, 2)
        return result
        

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/number-of-good-pairs/

上一篇

LeetCode 876 - 链表的中间结点

下一篇

LeetCode 231 - 2的幂