-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
84 lines (76 loc) · 1.71 KB
/
Copy pathSolution.java
File metadata and controls
84 lines (76 loc) · 1.71 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class FirstUnique
{
private final Map<Integer, Node> nodeMap = new HashMap<>();
private final Set<Integer> duplicates = new HashSet<>();
Node root;
Node tail;
public FirstUnique(int[] nums)
{
for (int num : nums)
{
add(num);
}
}
public int showFirstUnique()
{
if (root == null)
{
return -1;
}
return root.value;
}
public void add(int value)
{
if (nodeMap.containsKey(value))
{
Node node = nodeMap.get(value);
nodeMap.remove(value);
if (node == root)
{
root = node.next;
}
if (node == tail)
{
tail = node.previous;
}
if (node.previous != null)
{
node.previous.next = node.next;
}
if (node.next != null)
{
node.next.previous = node.previous;
}
duplicates.add(value);
}
else if (!duplicates.contains(value))
{
Node node = new Node(value);
nodeMap.put(value, node);
if (root == null)
{
root = node;
tail = node;
}
else
{
tail.next = node;
node.previous = tail;
tail = node;
}
}
}
class Node
{
private final int value;
Node next, previous;
Node(int value)
{
this.value = value;
}
}
}