zoukankan      html  css  js  c++  java
  • 414. Third Maximum Number

    https://leetcode.com/problems/third-maximum-number/#/description

    Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

    Example 1:

    Input: [3, 2, 1]
    
    Output: 1
    
    Explanation: The third maximum is 1.
    

    Example 2:

    Input: [1, 2]
    
    Output: 2
    
    Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
    

    Example 3:

    Input: [2, 2, 3, 1]
    
    Output: 1
    
    Explanation: Note that the third maximum here means the third maximum distinct number.
    Both numbers with value 2 are both considered as second maximum.


    Sol:

    Establish a list v,with three elements to store the largest, second largest and third largest number of the array. Traverse the array and check if the current number is larger than the first element in v, and put the larger number to the first place of list v. Then compare the current value to the second element in  list v and get the larger one to the second place of list v. Do this to third element in list v for the third time. In this way, we make sure:

    v = [largest number, second largest number, third largest number]

    return v[2] 

    class Solution(object):
        def thirdMax(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            
            # if len(nums) == 0:
            #    return None
            # elif len(nums) < 3:
            #    return max(nums)
            #else:
            v = [float('-inf'), float('-inf'), float('-inf')]
            for num in nums:
                if num not in v:
                    if num > v[0]:
                        v = [num, v[0],v[1]]
                    elif num > v[1]:
                        v = [v[0], num, v[1]]
                    elif num > v[2]:
                        v = [v[0], v[1], num]
            if float('-inf') in v:
                return max(nums)
            return v[2]

    Note:

    1 Make a list of three variables and keep comparing the current number with the current v[0], v[1] and v[2] and updating list v is the real trick here. 

  • 相关阅读:
    linux基础
    模块三、企业实战案例
    模块二、shell脚本逻辑结构
    模块一:shell 脚本基础
    三剑客、shell脚本
    定时任务、用户管理、磁盘介绍
    python笔记03
    文件属性、正则表达式、文件权限
    Linux系统目录结构介绍
    Linux基础及入门介绍
  • 原文地址:https://www.cnblogs.com/prmlab/p/6971500.html
Copyright © 2011-2022 走看看