TreeviewCopyright © aleen42 all right reserved, powered by aleen42

414. 第三大的数

https://leetcode-cn.com/problems/third-maximum-number/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-25 10:45:27
 * @Description: https://leetcode-cn.com/problems/third-maximum-number/
 * @FilePath: \leetcode-googtech\#414. Third Maximum Number\Solution.java
 */ 
class Solution {
    // Long.MIN_VALUE=-9223372036854775808(-2的63次方)
    private long MIN_VALUE = Long.MIN_VALUE;
    public int thirdMax(int[] nums) {
        // 初始化第一,第二以及第三大元素
        long firstElement = MIN_VALUE,secondElement = MIN_VALUE,thirdElement = MIN_VALUE;
        // 遍历数组,获取第一,第二以及第三大元素
        for(int num : nums) {
            if(num > firstElement) {
                thirdElement = secondElement;
                secondElement = firstElement;
                firstElement = num;
            }else if(secondElement < num && num < firstElement) {
                thirdElement = secondElement;
                secondElement = num;
            }else if (thirdElement < num && num < secondElement) {
                thirdElement = num;
            }
        }
        // 若无第三大元素则返回数组中的最大值
        return thirdElement==MIN_VALUE ? (int)firstElement : (int)thirdElement;
    }
}

Python

'''
@Author: Goog Tech
@Date: 2020-07-25 10:45:35
@Description: https://leetcode-cn.com/problems/third-maximum-number/
@FilePath: \leetcode-googtech\#414. Third Maximum Number\Solution.py
'''
class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 初始化第一,第二以及第三大元素
        # -sys.maxsize = -9223372036854775807
        first = second = thrid = -sys.maxsize
        # 遍历数组,获取第一,第二以及第三大元素的值
        for num in nums:
            if num > first:
                thrid, second, first = second, first, num
            elif second < num < first:
                thrid, second = second, num
            elif thrid < num < second:
                thrid = num
        # 若无第三大元素则返回最大元素的值
        return first if thrid == -sys.maxsize else thrid
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""