forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1429.java
45 lines (39 loc) · 1.28 KB
/
_1429.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
package com.fishercoder.solutions;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class _1429 {
public static class Solution1 {
/**
* Credit: https://leetcode.com/problems/first-unique-number/discuss/602698/Java-Easy-Set-O(1)
* <p>
* LinkedHashSet is a handy data structure to help preserve the order of all unique elements.
*/
public static class FirstUnique {
Set<Integer> uniqSet;
Set<Integer> nonUniqSet;
public FirstUnique(int[] nums) {
uniqSet = new LinkedHashSet<>();
nonUniqSet = new HashSet<>();
for (int num : nums) {
add(num);
}
}
public int showFirstUnique() {
if (!uniqSet.isEmpty()) {
return uniqSet.iterator().next();
}
return -1;
}
public void add(int value) {
if (uniqSet.contains(value)) {
uniqSet.remove(value);
nonUniqSet.add(value);
}
if (!nonUniqSet.contains(value)) {
uniqSet.add(value);
}
}
}
}
}