-
Notifications
You must be signed in to change notification settings - Fork 0
/
FirstUniqueNumber.java
49 lines (43 loc) · 1.12 KB
/
FirstUniqueNumber.java
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
// https://leetcode.com/problems/first-unique-number/
// #hash-table #design
class FirstUnique {
private Deque<Integer> uniqueQueue;
private HashSet<Integer> duplicateSet;
private HashSet<Integer> uniqueSet;
private void internalAdd(int num) {
if (uniqueSet.isEmpty() || !uniqueSet.contains(num)) {
uniqueSet.add(num);
uniqueQueue.addLast(num);
} else {
duplicateSet.add(num);
}
}
public FirstUnique(int[] nums) {
uniqueQueue = new LinkedList<>();
uniqueSet = new HashSet<>();
duplicateSet = new HashSet<>();
for (int num : nums) {
internalAdd(num);
}
}
public int showFirstUnique() {
int ret = -1;
while (!uniqueQueue.isEmpty()) {
int v = uniqueQueue.peekFirst();
if (duplicateSet.contains(v)) {
uniqueQueue.pollFirst();
} else {
ret = v;
break;
}
}
return ret;
}
public void add(int value) {
internalAdd(value);
}
}
/**
* Your FirstUnique object will be instantiated and called as such: FirstUnique obj = new
* FirstUnique(nums); int param_1 = obj.showFirstUnique(); obj.add(value);
*/