LeetCode1512. 好数对的数目

一. 题目
  1. 问题
    给你一个整数数组 nums 。
    如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。
    返回好数对的数目。

  2. 示例
    在这里插入图片描述

二. 方法一
  1. 解题思路

  2. 解题代码

def numIdenticalPairs(self, nums: List[int]) -> int:
    count = 0
    for i in range(0, len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] == nums[j]:
                count += 1
    return count
  1. 分析
    时间复杂度: O(n^2)
    空间复杂度: O(1)
三. 方法二: 高斯求和
  1. 解题思路

    1. 先对列表进行排序
    2. 再计算出每组数字的个数
    3. 高斯求和
  2. 解题代码

    def numIdenticalPairs(self, nums: List[int]) -> int:
        nums.sort()
        count = 0
        num = 1
        for i in range(0, len(nums) - 1):
            if nums[i] == nums[i + 1]:
                num += 1
            else:
                if num != 1:
                    count += num * (num - 1) / 2
                    num = 1
        if num != 1:
            count += num * (num - 1) / 2
        return int(count)
    
  3. 分析
    时间复杂度: O(nlogn)
    空间复杂度: O(1)

四. 方法三:(方法二的优化, 用map存储)
  1. 解题思路

    1. 用map存储相同元素的数量(key为元素, value为数量)
    2. 再使用高斯求和计算最终的结果
  2. 解题代码

    def numIdenticalPairs(self, nums: List[int]) -> int:
        map = {}
        count = 0
        for ele in nums:
            if ele not in map.keys():
                map[ele] = 1
            else:
                map[ele] += 1
        for key in map.keys():
            if map[key] >= 2:
                count += map[key] * (map[key] - 1) // 2
    
        return count
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值