LeetCode 1512 Number of Good Pairs (Python)

Posted by 小明MaxMing on July 11, 2020

题目

Given an array of integers nums.

A pair (i,j) is called good if nums[i] == nums[j] and i < j.

Return the number of good pairs.

解题思路

  1. 枚举i j,进行比较
  2. 计算每个数出现的次数n,那么可以构成N * (n - 1)/ 2

代码

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        n = len(nums)
        res = 0
        for i in range(n - 1):
            for j in range(i + 1, n):
                if nums[i] == nums[j]:
                    res += 1
        return res
class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        return sum(v * (v - 1) // 2 for v in Counter(nums).values())

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅