414. 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.


easy 题目基本没什么算法可言。找三个最大的数,注意不够三个数的情况(没有出现三个及以上数值不同的数) 以及在数组中出现MIN_VALUE的情况

bugfree需要强化,在每次写之前都把能想到的corner写下来  写完程序之后对照一遍这些坑有没有漏



public class Solution {
    public int thirdMax(int[] nums) {
        int min1=Integer.MIN_VALUE;
        int min2=Integer.MIN_VALUE;
        int min3=Integer.MIN_VALUE;
        boolean flag=false;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==Integer.MIN_VALUE)
                flag=true;
            if(nums[i]==min1||nums[i]==min2||nums[i]==min3)
                continue;
                
            if(nums[i]>min3){
                min3=nums[i];
            }
            if(min3>min2){
                int temp=min2;
                min2=min3;
                min3=temp;
            }
            if(min2>min1){
                int temp=min1;
                min1=min2;
                min2=temp;
            }
        }
       if(min3!=Integer.MIN_VALUE||(flag&&min2!=Integer.MIN_VALUE))
            return min3;
        else return min1;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值