414. Third Maximum Number

题目摘要
给定一个非空数组,找出其中第三大的数,如果没有,找出其中最大的数。时间复杂度必须控制在 O(n) 内。

解法
int max, mid, min,赋值为整形最小值。遍历数组,按大小情况替换max, mid, min, 最后判断有没有第三大的数,返回。

public class Solution {
    public int thirdMax(int[] nums) {
        int max, mid, min;
        max = mid = min = Integer.MIN_VALUE;
        //检查nums中是否有Integer.MIN_VALUE;
        boolean hasMin = false;
        for (int x : nums) {
            if (x == Integer.MIN_VALUE) hasMin = true;
            if (x == max || x == mid) continue;
            if ( x > max) {
                min = mid;
                mid = max;
                max = x;
            } else if (x > mid) {
                min = mid;
                mid = x;
            } else if (x > min) {
                min = x;
            }
        }
        if (mid == Integer.MIN_VALUE) {
            return max;
        } else if (min == Integer.MIN_VALUE) {
            if (hasMin) return min;
            else return max;
        } else {
            return min;
        }
    }
}

注意

  • 如何判断有没有第三大的数
    在遍历的同时检查数组里有没有Integer.MIN_VALUE,再结合max, mid, min中有没有该值来判断据此来判断。

可问问题

原题
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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值