[LeetCode] First Unique Number

1429. First Unique Number

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.
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
class FirstUnique {
unordered_map<int, int> mp;
queue<int> q;
public:
FirstUnique(vector<int>& nums) {
for(auto& n : nums) mp[n]++;
for(auto& n : nums) {
if(mp[n] == 1) q.push(n);
}
}

int showFirstUnique() {
while(!q.empty() and mp[q.front()] >= 2) q.pop();
return q.empty() ? -1 : q.front();
}

void add(int value) {
mp[value]++;
if(mp[value] >= 2) return;
q.push(value);
}
};

/**
* Your FirstUnique object will be instantiated and called as such:
* FirstUnique* obj = new FirstUnique(nums);
* int param_1 = obj->showFirstUnique();
* obj->add(value);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/06/PS/LeetCode/first-unique-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.