Leetcode哈希表相关题目总结(1)414. 第三大的数

题目414. 第三大的数

题目描述:

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
示例

自己的解法

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dict = {}
        li=[]
        for m in nums:
            dict[m] = dict.get(m, 0) + 1
        if len(dict)<=2:
            return(max(nums))
        else:
            for x,y in dict.items():
                li.append(x)
            li.sort()
            return(li[len(li)-3])

别人的解法

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        tmp = list(set(nums))
        tmp.sort(reverse = True)
        if len(tmp) < 3:
            return tmp[0]
        else:
            return tmp[2]

思路比较

我的方法
(1)先用字典统计原数组出现的元素与对应的次数
(2)判断统计后的元素数量:
如果<3,则返回最大的数;
如果≥3,将字典的键存入新的数组中并排序,返回第三大的数。

别人的方法
列表去重—>排序—>根据情况返回

用时、内存区别

在这里插入图片描述

代码改进

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dict = {}
        for m in nums:
            dict[m] = dict.get(m, 0) + 1  #统计
        dictN=sorted(dict.items(),key=lambda x:x[0],reverse=True) #排序
        if len(dict)<=2: #根据情况返回
            return(dictN[0][0])
        else:
            return(dictN[2][0])            

代码笔记

1.字典的排序方法:

dictN=sorted(dict.items(),key=lambda x:x[0],reverse=True) 
#dict为待排序字典,sorted()函数第一个参数为待排序的集合,序列(列表,字符串,元组),字典等;
#第一个参数key为排序参照,即以字典的哪个元素为准进行排序;
#第三个参数reverse可以为true或者false,false为默认排序(从小到大),true为反序从大到小
  1. dict为待排序字典,sorted()函数第一个参数为待排序的集合,序列(列表,字符串,元组),字典等;
  2. 第一个参数key为排序参照,即以字典的哪个元素为准进行排序;
  3. 第三个参数reverse可以为true或者false,false为默认排序(从小到大),true为反序从大到小。

2.词频(元素出现次数的统计)

for m in nums:
	dict[m] = dict.get(m, 0) + 1

3.列表去重与排序

 tmp = list(set(nums))
 tmp.sort(reverse = True)

总结

  1. 第一次刷题,很多最基本的操作都不会,有思路但是不会写代码,需要多练习;
  2. 同时,还需要回顾列表、字典等基本操作;
  3. 整理一篇python列表与数组的基本操作与区别。
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值