leetcode 1512. Number of Good Pairs(python)

描述

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.

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

Note:

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

解析

根据题意,只需要用字典结构统计出现的字符和对应的出现次数,然后遍历字典,将大于等于 2 的字符的出现次数,都按照公式 n*(n-1)/2 ,计算该字母能形成合法的 (i,j) 组合的次数,最后求和即可得到答案。如果编程经验丰富一行代码即可解决。

解答

class Solution(object):
    def numIdenticalPairs(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = 0
        for v in collections.Counter(nums).values():
            if v>1:
                res += v*(v-1)/2
        return res

运行结果

Runtime: 12 ms, faster than 98.96% of Python online submissions for Number of Good Pairs.
Memory Usage: 13.4 MB, less than 73.07% of Python online submissions for Number of Good Pairs.

原题链接:https://leetcode.com/problems/number-of-good-pairs/

您的支持是我最大的动力

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/115401034
今日推荐