forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
first-unique-number.cpp
86 lines (74 loc) · 1.98 KB
/
first-unique-number.cpp
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
85
86
// Time: ctor: O(k)
// add: O(1)
// showFirstUnique: O(1)
// Space: O(n)
class FirstUnique {
public:
FirstUnique(vector<int>& nums) {
for (const auto& num : nums) {
add(num);
}
}
int showFirstUnique() {
if (q_.size()) {
return q_.front().first;
}
return -1;
}
void add(int value) {
if (!dup_.count(value) && !q_.count(value)) {
q_[value] = true;
return;
}
if (q_.count(value)) {
q_.pop(value);
dup_.emplace(value);
}
}
private:
template<typename K, typename V>
class OrderedDict {
public:
bool count(const K& key) const {
return map_.count(key);
}
V& operator[](const K& key) {
if (!map_.count(key)) {
list_.emplace_front();
list_.begin()->first = key;
map_[key] = list_.begin();
}
return map_[key]->second;
}
void popitem() {
auto del = list_.front(); list_.pop_front();
map_.erase(del.first);
}
pair<K, V> front() {
return *list_.crbegin();
}
void pop(const K& key) {
if (!map_.count(key)) {
return;
}
list_.erase(map_[key]);
map_.erase(key);
}
vector<K> keys() const {
vector<K> result;
transform(list_.crbegin(), list_.crend(), back_inserter(result),
[](const auto& x) {
return x.first;
});
return result;
}
int size() const {
return list_.size();
}
private:
list<pair<K, V>> list_;
unordered_map<K, typename list<pair<K, V>>::iterator> map_;
};
OrderedDict<int, bool> q_;
unordered_set<int> dup_;
};