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
Example
Example 1:
Input:
add(1)
add(2)
firstUnique()
add(1)
firstUnique()
Output:
[1,2]
Example 2:
Input:
add(1)
add(2)
add(3)
add(4)
add(5)
firstUnique()
add(1)
firstUnique()
add(2)
firstUnique()
add(3)
firstUnique()
add(4)
firstUnique()
add(5)
add(6)
firstUnique()
Output:
[1,2,3,4,5,6]
Notice
You can assume that there must be at least one unique number in the stream when calling the firstUnique.
思路:跟First Unique Number in Data Stream一模一样;
因为data只能够access一次,我们要快速的access一个node,而且如果发现不是答案,需要O(1)去delete一个node,而且需要有顺序,那么只能是linkedlist + HashMap. 因为是linkedlist,delete需要前面的node,所以hashmap里面可以存prev node。
PS:如果不要求有顺序,arraylist就可以实现,(把最后一个赋值给前面的点就行)
public class DataStream {
private class Node {
public Node next;
int value;
public Node (int value) {
this.value = value;
this.next = null;
}
}
// num, prevNode;
HashMap<Integer, Node> hashmap;
Node dummpy;
Node cur;
public DataStream(){
this.hashmap = new HashMap<Integer, Node>();
this.dummpy = new Node(0);
this.cur = dummpy;
}
/**
* @param num: next number in stream
* @return: nothing
*/
public void add(int num) {
if(!hashmap.containsKey(num)) {
Node node = new Node(num);
cur.next = node;
hashmap.put(num, cur);
cur = cur.next;
} else {
// contains num;
Node prev = hashmap.get(num);
if(prev != null) {
prev.next = prev.next.next;
if(prev.next != null) {
int prevNextValue = prev.next.value;
hashmap.put(prevNextValue, prev);
} else {
//prev.next == null,代表是delete最后一个元素,所以cur = prev
cur = prev;
}
hashmap.put(num, null);
}
}
}
/**
* @return: the first unique number in stream
*/
public int firstUnique() {
if(dummpy.next == null) {
return -1;
} else {
return dummpy.next.value;
}
}
}