-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1429-first-unique-number.cpp
47 lines (42 loc) · 1.54 KB
/
1429-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
// Title: First Unique Number
// Description:
// You have a queue of integers, you need to retrieve the first unique integer in the queue.
// Implement the FirstUnique class:
// FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
// int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer.
// void add(int value) insert value to the queue.
// Link: https://leetcode.com/problems/first-unique-number/
// Time complexity: O(1) for { showFirstUnique(), add(value) }
// Space complexity: O(n)
class FirstUnique {
private:
list<int> uniqueList;
unordered_map<int,list<int>::iterator> uniqueMap;
unordered_set<int> duplicatedSet;
public:
FirstUnique(vector<int> &nums) {
for (int num: nums)
add(num);
}
int showFirstUnique() {
return !uniqueList.empty() ? uniqueList.front() : -1;
}
void add(int value) {
if (duplicatedSet.count(value) != 0) {
return;
} else if (uniqueMap.count(value) != 0) {
uniqueList.erase(uniqueMap.at(value));
uniqueMap.erase(value);
duplicatedSet.emplace(value);
} else {
uniqueList.emplace_back(value);
uniqueMap.emplace(value, std::prev(uniqueList.end()));
}
}
};
/**
* Your FirstUnique object will be instantiated and called as such:
* FirstUnique* obj = new FirstUnique(nums);
* int param_1 = obj->showFirstUnique();
* obj->add(value);
*/