首页 > 代码库 > Leetcode: Third Maximum Number

Leetcode: 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.

My Solution:

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

Highest votes in discussion

 1 public int thirdMax(int[] nums) {
 2         int max, mid, small, count;
 3         max = mid = small = Integer.MIN_VALUE;
 4         count = 0;  //Count how many top elements have been found.
 5 
 6         for( int x: nums) {
 7             //Skip loop if max or mid elements are duplicate. The purpose is for avoiding right shift.
 8             if( x == max || x == mid ) {
 9                 continue;
10             }
11 
12             if (x > max) {
13                 //right shift
14                 small = mid;
15                 mid = max;
16 
17                 max = x;
18                 count++;
19             } else if( x > mid) {
20                 //right shift
21                 small = mid;
22 
23                 mid = x;
24                 count++;
25             } else if ( x >= small) { //if small duplicated, that‘s find, there‘s no shift and need to increase count.
26                 small = x;
27                 count++;
28             }
29         }
30 
31         //"count" is used for checking whether found top 3 maximum elements.
32         if( count >= 3) { 
33             return small;
34         } else {
35             return max;
36         }
37     }

 

Leetcode: Third Maximum Number