当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.414.Third Maximum Number 数组中第三大的数

LeetCode.414.Third Maximum Number 数组中第三大的数

题目描述

414 Third Maximum Number
https://leetcode-cn.com/problems/third-maximum-number/

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.

解题过程

相似题目
LeetCode.628.Maximum Product of Three Numbers 数组中三个数的最大乘积
LeetCode.414.Third Maximum Number 数组中第三大的数

维护最大、次大、三大三个遍历, O(n) 遍历过程中不断比较更新这三个变量即可。
时间复杂度 O(n) 空间复杂度 O(1)

private static class SolutionV2020 {
    public int thirdMax(int[] nums) {
        Integer max = null, secondMax = null, thirdMax = null;
        for (int n : nums) {
            if (null == max || n > max) {
                thirdMax = secondMax;
                secondMax = max;
                max = n;
            } else if (n < max && (null == secondMax || n > secondMax)) {
                thirdMax = secondMax;
                secondMax = n;
            } else if ((secondMax != null && n < secondMax) && (thirdMax == null || n > thirdMax)) {
                thirdMax = n;
            }
        }
        return thirdMax != null ? thirdMax : max;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_414_ThirdMaximumNumber.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_414_ThirdMaximumNumber.java


上一篇 LeetCode.200.Number of Islands 岛屿个数

下一篇 LeetCode.347.Top K Frequent Elements 前K个高频元素

阅读
评论
288
阅读预计1分钟
创建日期 2020-02-25
修改日期 2020-02-25
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论