美文网首页
Data Stream

Data Stream

作者: 谢谢水果 | 来源:发表于2018-12-13 07:45 被阅读0次

    http://www.lintcode.com/tag/data-stream/

    lt960. First Unique Number in a Stream II

    每个操作都是O(1)

    public class DataStream {
        class ListNode{
            int value;
            ListNode next;
            ListNode(int value){
                this.value = value;
            }
        }
        Map<Integer, ListNode> map = new HashMap<>();
        Set<Integer> set = new HashSet<>();
        ListNode dummy, tail;
        public DataStream(){
            // do intialization if necessary
            dummy = new ListNode(0);
            tail = dummy;
        }
        /**
         * @param num: next number in stream
         * @return: nothing
         */
        public void add(int num) {
            // write your code here
            if(set.contains(num)){
                if(map.containsKey(num)){
                    ListNode pre = map.get(num);
                    if(pre.next==tail){
                        tail = pre;
                    }else{
                        map.put(pre.next.next.value, pre);
                        pre.next = pre.next.next;
                    }
                    map.remove(num);
                }
            }else{
                ListNode newNode = new ListNode(num);
                tail.next = newNode;
                map.put(num, tail);
                tail = newNode;
                set.add(num);
            }
        }
    
        /**
         * @return: the first unique number in stream
         */
        public int firstUnique() {
            // write your code here
            return dummy.next.value;
        }
    }
    

    相关文章

      网友评论

          本文标题:Data Stream

          本文链接:https://www.haomeiwen.com/subject/bknyhqtx.html