Given a continuous stream of data, write a function that returns the first unique number (including the last number) when the terminating number arrives. If the unique number is not found, return -1
.
Example
Example1
Input:
[1, 2, 2, 1, 3, 4, 4, 5, 6]
5
Output: 3
Example2
Input:
[1, 2, 2, 1, 3, 4, 4, 5, 6]
7
Output: -1
Example3
Input:
[1, 2, 2, 1, 3, 4]
3
Output: 3
思路:因为data只能够access一次,我们要快速的access一个node,而且如果发现不是答案,需要O(1)去delete一个node,而且需要有顺序,那么只能是linkedlist + HashMap. 因为是linkedlist,delete需要前面的node,所以hashmap里面可以存prev node。
PS:如果不要求有顺序,arraylist就可以实现,(把最后一个赋值给前面的点就行)
public class Solution {
/**
* @param nums: a continuous stream of numbers
* @param number: a number
* @return: returns the first unique number
*/
private class DataStream {
private class Node {
public Node next;
public int value;
public Node(int value) {
this.value = value;
this.next = null;
}
}
private HashMap<Integer, Node> hashmap;
private Node dummpy;
private Node cur;
public DataStream() {
hashmap = new HashMap<Integer, Node>();
dummpy = new Node(0);
cur = dummpy;
}
public void add(int value) {
if(!hashmap.containsKey(value)) {
Node node = new Node(value);
cur.next = node;
hashmap.put(value, cur);
cur = cur.next;
} else {
// contains duplicate key;
Node prev = hashmap.get(value);
if(prev != null) {
prev.next = prev.next.next;
if(prev.next != null) {
int prevNextValue = prev.next.value;
hashmap.put(prevNextValue, prev);
} else {
//这里很重要,别忘记了,如果delete掉是最后一个元素,那么cur = prev;
cur = prev;
}
//这里很巧妙的,如果是第二次遇见,那么直接设置node为null,
//但是hashmap里面还是保留key,表示遇见过;
hashmap.put(value, null);
}
}
}
public int getFirstUnique() {
if(dummpy.next != null) {
return dummpy.next.value;
} else {
return -1;
}
}
}
public int firstUniqueNumber(int[] nums, int number) {
if(nums == null || nums.length == 0) {
return -1;
}
DataStream ds = new DataStream();
for(int i = 0; i < nums.length; i++) {
ds.add(nums[i]);
if(nums[i] == number){
return ds.getFirstUnique();
}
}
return -1;
}
}