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

题目分析

题目让我们返回一组数中重复数字的pair的个数,并且每一对数字中,第一个数的位数比第二个数的位数小。

方案一(brute force)

用两个循环遍历数组,第二个循环从第一个循环的当前值+1 开始循环。当第二个循环遇到第一个循环的当前数值时,就让计数+1.

方案二(等差数列)

只用一个循环,并且使用Python自带的 colllections库的 Counter。Counter形成的是一个字典,其中每一个元素是Key, 其个数是values。

以example 2为例, nums = [1,1,1,1]

用位数为 0 的 ‘1’ 去找相同并且位数大于自己的数,有3种情况(这里都列的是位数):[0,1], [0,2], [0,3]
用位数为 1 的 ‘1’ 去找相同并且位数大于自己的数,有2种情况:[1,2], [1,3]
用位数为 2 的 ‘1’ 去找相同并且位数大于自己的数,有1种情况:[2,3]
用位数为 3 的 ‘1’ 去找相同并且位数大于自己的数,有0种情况

总共有6种情况,6= 3+2+1,这个规律也适用于其他情况,所以是可以用等差数列来求得某一个数所有的组合情况。

代码实现

方案一(brute force)

class Solution(object):
    def numIdenticalPairs(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0 
        N = len(nums)
        
        for i in range(N):
            for j in range(i+1,N):
                if nums[i] == nums[j]:
                    count += 1
        return count

方案二(等差数列)

class Solution(object):
    def numIdenticalPairs(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        ans = 0 
        count = collections.Counter(nums) 
        
        for k in count: 
            if count[k]>1: # collections.Counter这里[k], 返回的是某个element的个数
                ans += count[k]*(count[k]-1)/2 # 公式是(首项+末项)*项数/2 
                							   # = (1+(n-1))*(n-1)/2 =n(n-1)/2
        return ans              

日期

2021-1-31 #1512 方案一&二

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值