栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Leetcode小白---刷题记录20211007

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode小白---刷题记录20211007

题目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列表与数组的基本操作与区别。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/302347.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号