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.
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^8
1 <= value <= 10^8
- At most
50000
calls will be made toshowFirstUnique
andadd
.
你有一個整數組成的佇列,你需要找到在此佇列中第一個只有出現一次的整數。
實作
FirstUnique
類別:
FirstUnique(int[] nums)
用一串數字佇列初始化該物件。int showFirstUnique()
回傳佇列中第一個只有出現一次的整數,如果沒有這種數字回傳-1
void add(int value)
新增一個新的數到佇列中。
限制:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^8
1 <= value <= 10^8
- 最多呼叫
50000
次showFirstUnique
和add
.
unique
是一個list,儲存只出現一次的數字。it
是一個加速用的hash,key是想要找的數字,value,是該數字在list中的指標。(用於快速刪除)allNums
是一個用於確認數字是否第一次出現的hash。add
進去就好了。showFirstUnique
只要去找unique
這個list就好了。add
是最麻煩的部分,我們先確認allNums
有沒有這個數字:
unique
裡面,並且把it
綁上去。it
映射過去,去unique
找到並移除該數字。allNums
的計數要加上去。LeetCode
C++