zoukankan      html  css  js  c++  java
  • 414. 第三大的数

     

    两中写法都过了。

    学到的是sorted()函数排其他可迭代对象后返回值是list类型。

    代码一:

     1 class Solution(object):
     2     def thirdMax(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         # 转set去重
     8         s = set(nums)
     9         # 在转回list
    10         # nums = list(s)
    11         # 降序排
    12         # nums.sort(reverse=True)
    13         # sorted()函数排序后返回的是list类型
    14         nums = sorted(s, reverse=True)
    15         if len(s) < 3:
    16             return nums[0]
    17         else:
    18             return nums[2]

    代码二:

     1 class Solution(object):
     2     def thirdMax(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         # 升序排
     8         nums.sort()
     9         index = 1
    10         # 暂存nums最后一个元素
    11         temp = nums[-1]
    12         # 从倒数第二个元素倒序遍历
    13         for j in range(len(nums) - 2, -1, -1):
    14             if index == 3:
    15                 return temp
    16             if nums[j] == temp:
    17                 nums.pop(j)
    18             else:
    19                 temp = nums[j]
    20                 index += 1
    21         if index != 3:
    22             return nums[-1]
    23         else:
    24             return temp
  • 相关阅读:
    更多的bash shell命令
    Docker(一)Docker概述
    SpringCloud(一)版本选择
    Scala 技术笔记之 可变长参数
    嵌入式 ThriftServer in Spark
    Spark 代码走读之 Cache
    Scala 技术笔记之 Option Some None
    Spark作业执行
    Shuffle
    Jetty初探
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12757650.html
Copyright © 2011-2022 走看看