-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode414.java
More file actions
66 lines (59 loc) · 1.77 KB
/
LeetCode414.java
File metadata and controls
66 lines (59 loc) · 1.77 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.PriorityQueue;
import java.util.HashSet;
import java.util.TreeSet;
public class LeetCode414 {
public static void main(String[] args) {
// 输入:[3, 2, 1]
// 输出:1
System.out.println(new Solution414_2().thirdMax(new int[] { 3, 2, 1 }));
// 输入:[1, 2]
// 输出:2
System.out.println(new Solution414_2().thirdMax(new int[] { 1, 2 }));
// 输入:[2, 2, 3, 1]
// 输出:1
System.out.println(new Solution414_2().thirdMax(new int[] { 2, 2, 3, 1 }));
// 输入:[1,2,2,5,3,5]
// 输出:2
System.out.println(new Solution414_2().thirdMax(new int[] { 1, 2, 2, 5, 3, 5 }));
}
}
class Solution414_1 {
public int thirdMax(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
continue;
}
set.add(nums[i]);
if (pq.size() < 3) {
pq.add(nums[i]);
} else {
if (pq.peek() < nums[i]) {
pq.poll();
pq.add(nums[i]);
}
}
}
if (set.size() < 3) {
while (pq.size() > 1) {
pq.poll();
}
return pq.peek();
} else {
return pq.peek();
}
}
}
class Solution414_2 {
public int thirdMax(int[] nums) {
TreeSet<Integer> s = new TreeSet<Integer>();
for (int num : nums) {
s.add(num);
if (s.size() > 3) {
s.remove(s.first());
}
}
return s.size() == 3 ? s.first() : s.last();
}
}