First Unique Number in Data Stream II

We need to implement a data structure named DataStream. There are two methods required to be implemented:

  1. void add(number) // add a new number
  2. int 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;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值