forked from pxu/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThirdMax.java
More file actions
34 lines (29 loc) · 1.08 KB
/
ThirdMax.java
File metadata and controls
34 lines (29 loc) · 1.08 KB
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
30
31
32
33
34
public class ThirdMax {
public int thirdMax(int[] nums) {
Integer first = null;
Integer second = null;
Integer third = null;
for(int i=0; i<nums.length; ++i) {
Integer ii = nums[i];
if(ii.equals(first) || ii.equals(second) || ii.equals(third)) continue; // avoid duplicates
if(first == null || nums[i] > first) {
third = second;
second = first;
first = nums[i];
} else if(second == null || nums[i] > second) {
third = second;
second = nums[i];
} else if(third == null || nums[i] > third) {
third = nums[i];
}
System.out.println("first : " + first + "\t" + "second : " + second + "\t" + "third : " + third + "\n");
}
return third == null? first: third;
}
public static void main(String[] args) {
int[] nums = new int[] {2, 2, 3, 1};
ThirdMax tm = new ThirdMax();
int thirdMx = tm.thirdMax(nums);
System.out.println(nums);
}
}