960. First Unique Number in a Stream II
We need to implement a data structure named DataStream
. There are two
methods required to be implemented:
void add(number)
// add a new numberint firstUnique()
// return first unique number
样例
add(1)
add(2)
firstUnique() => 1
add(1)
firstUnique() => 2
注意事项
You can assume that there must be at least one unique number in the stream when calling the firstUnique.
实现思路:
用一个队列和一个hash表,数字依次存入队列,用hash表记录表中数字的个数,每次都从头开始遍历队列,返回第一个first unique。
class DataStream:
def __init__(self):
# do intialization if necessary
self.queue = []
self.hashmap = {}
"""
@param num: next number in stream
@return: nothing
"""
def add(self, num):
# write your code here
self.queue.append(num)
self.hashmap[num] = self.hashmap.get(num, 0) + 1
"""
@return: the first unique number in stream
"""
def firstUnique(self):
# write your code here
for i in range(len(self.queue)):
if self.hashmap[self.queue[i]] == 1:
#只是返回这个数,并不从数组中删除,让没有相同的数加入时,first unique一直是这个数。
return self.queue[i]
return -1