-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfirst_unique_number_design.cpp
43 lines (40 loc) · 1.08 KB
/
first_unique_number_design.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
class FirstUnique {
public:
list <int> q;
unordered_map <int, pair<int, list <int>::iterator>> mp;
FirstUnique(vector<int>& nums) {
for(int i=0; i<nums.size(); i++)
{
add(nums[i]);
}
}
int showFirstUnique() {
if(mp[q.front()].first == 1)
return q.front();
else
return -1;
}
void add(int value) {
if(mp.find(value)!=mp.end())
{
auto it = mp.find(value);
// get iterator in queue for value and remove it from there and insert it at the end.
if((it->second).second != q.end())
q.erase((it->second).second);
mp[value].second = q.end();
mp[value].first++;
}
else
{
q.push_back(value);
mp[value].first++;
mp[value].second = prev(q.end());
}
}
};
/**
* Your FirstUnique object will be instantiated and called as such:
* FirstUnique* obj = new FirstUnique(nums);
* int param_1 = obj->showFirstUnique();
* obj->add(value);
*/