题目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为反序从大到小
- dict为待排序字典,sorted()函数第一个参数为待排序的集合,序列(列表,字符串,元组),字典等;
- 第一个参数key为排序参照,即以字典的哪个元素为准进行排序;
- 第三个参数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)
总结
- 第一次刷题,很多最基本的操作都不会,有思路但是不会写代码,需要多练习;
- 同时,还需要回顾列表、字典等基本操作;
- 整理一篇python列表与数组的基本操作与区别。