-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThirdMax.java
More file actions
29 lines (21 loc) · 839 Bytes
/
Copy pathThirdMax.java
File metadata and controls
29 lines (21 loc) · 839 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// https://leetcode.com/problems/third-maximum-number/ fb/ git/ li
public class Solution {
public int thirdMax(int[] nums) {
if (nums.length < 3) return (nums[0] < nums[1]) ? nums[1] : nums[0];
long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE;
for(int i = 0; i < nums.length; i++) {
int n = nums[i];
if(n > first) {
third = second;
second = first;
first = n;
} else if(n > second && n < first) {
third = second;
second = n;
} else if(n > third && n < second) {
third = n;
}
}
return (third==Long.MIN_VALUE) ? (int) first : (int) third;
}
}