180.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).

给定非空的整数数组,返回此数组中的第三个最大数字。 如果不存在,则返回最大数量。 时间复杂度必须在O(n)中。

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.
说明:第三个最大值为1。

 

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
说明:第三个最大值不存在,因此返回最大值(2)。

 

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.
值为2的两个数字都被视为第二个最大值。

解答:

 1 class Solution {
 2     public int thirdMax(int[] nums) {
 3         long max1=Long.MIN_VALUE;
 4         long max2=Long.MIN_VALUE;
 5         long max3=Long.MIN_VALUE;
 6         
 7         for(long num:nums){
 8             if(num>max1){
 9                 max3=max2;
10                 max2=max1;
11                 max1=num;
12             }else if(num<max1 && num>max2){
13                 max3=max2;
14                 max2=num;
15             }else if(num<max2 && num>max3){
16                 max3=num;
17             }
18         }
19         
20         return max3==Long.MIN_VALUE ? (int)max1:(int)max3;
21     }
22 }

详解:

注意:

初始化要用长整型Long.MIN_VALUE,否则当数组中有Int.MIN_VALUE恰好是第三大的数字,程序就不知道该返回MIN_VALUE还是最大值了

posted @ 2018-09-20 15:00  chan_ai_chao  阅读(98)  评论(0编辑  收藏  举报