- First Unique Number In Stream
LC:387
- A follow-up of 2018-10-19 First Unique Character in a String [E]
- Strongly related to 2018-10-23/24 LRU Cache [H]
Given a continuous stream of numbers, write a function that returns the first unique number whenever terminating number is reached(include terminating number). If there no unique number before terminating number or you can't find this terminating number, return -1.
Example
Given a stream [1, 2, 2, 1, 3, 4, 4, 5, 6] and a number 5
return 3
Given a stream [1, 2, 2, 1, 3, 4, 4, 5, 6] and a number 7
return -1
class LinkedNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self,):
self.hash = {}
self.head = LinkedNode()
self.tail = self.head
"""
@param nums: a continuous stream of numbers
@param number: a number
@return: returns the first unique number
"""
def firstUniqueNumber(self, nums, number):
if not nums:
return -1
for n in nums:
if n in self.hash:
if self.hash[n]:
self.remove(self.hash[n])
else:
self.push_back(LinkedNode(n))
if n == number:
return self.head.next.val
return -1
def push_back(self, node):
self.hash[node.val] = self.tail
self.tail.next = node
self.tail = node
# different from LRU, need to totally reomove
# use self.hash[node] to denote that node is deleted
def remove(self, prev):
node = prev.next
prev.next = node.next
if node == self.tail:
self.tail = prev
else:
self.hash[node.next.val] = prev
self.hash[node.val] = None
Note:
-
Almost the same to 2018-10-23/24 LRU Cache [H]
- need
LinkedNode()
- same
push_back()
- same
__init__()
, needhash(value, prev node)
- need
-
But different in:
-
remove()
instead ofmove_to_back()
- set
hash[val]
to beNone
if deleted, becausehash
still works as"visited"
-
-
A really good way of practicing linked list
- Learn how to
add
,remove
etc. - Consider edge cases.
- tail of linked list in
remove()
- what if a node is deleted
- tail of linked list in
- Learn how to