CS
Algorithm
Algorithm
  • lintcode
  • EPI
    • String
      • Base Convert
  • Graph
    • Inorder Successor in BST
    • Balanced Binary Tree
    • All Paths From Source to Target
  • LinkedIn
    • House robber II
    • Single Number
    • Flatten Binary Tree to Linked List
    • Smallest Difference pair of values between two unsorted Arrays
    • Word Search II
    • Implement Trie (Prefix Tree)
    • K Closest Points
    • implement BST
    • HashMap
    • Implement strStr()
    • Min Stack
    • Meeting Rooms
    • Shortest Completing Word
    • Longest Palindromic Substring
    • Longest Palindromic Subsequence
    • Count Different Palindromic Subsequences
    • Palindromic Substrings
    • Sparse Matrix Multiplication
    • Insert Delete GetRandom O(1) - Duplicates allowed
    • Bulb Switcher
    • Verify Preorder Sequence in Binary Search Tree
    • Untitled
    • Find the Celebrity
    • Coin Change
    • Partition Equal Subset Sum
    • Permutation Sequence
    • Next Permutation
    • Kth Smallest Element in a BST
    • Word Search
    • Word Break
    • Shuffle an Array
    • Add Two Numbers
    • Longest Substring Without Repeating Characters
    • Longest Increasing Subsequence
    • 3Sum Smaller
    • LFU Cache
    • Copy List with Random Pointer
    • Linked List Cycle
    • Merge Sorted Array
    • Two Sum II - Input array is sorted
    • Search Insert Position
    • Find First and Last Position of Element in Sorted Array
    • Combination Sum
    • Path Sum
    • Roman to Integer
    • Valid Parentheses
    • Product of Array Except Self
    • Permutations
    • 3Sum
    • Reverse Integer
    • Longest Common Subsequence and substring
    • Implement Stack using Queues
    • Sort Characters By Frequency
    • Delete Node in a BST
    • Invert Binary Tree
    • Serialize and Deserialize BST
    • Reverse String
    • Binary Tree Zigzag Level Order Traversal
    • Friend Circles
    • Letter Combinations of a Phone Number
    • Fizz Buzz
    • Encode and Decode TinyURL
    • Binary Tree Right Side View
    • Shortest Word Distance III
    • Binary Search Tree Iterator
    • Kth Largest Element in an Array
    • Clone Graph
    • Lowest Common Ancestor III
    • Lowest Common Ancestor II
    • Reverse Words in a String
    • Path Sum
    • Find K Pairs with Smallest Sums
    • Validate Binary Search Tree
    • All O`one Data Structure
    • Top K Frequent Elements
    • Integer to Roman
    • Shortest Word Distance III
    • Edit Distance
    • Profitable Schemes
    • Minimum Window Substring
    • LRU Cache
    • Text Justification
    • Integer to English Words
    • Partition to K Equal Sum Subsets
    • Graph Valid Tree
    • Exclusive Time of Functions
    • Repeated DNA Sequences
    • Valid Number
    • Insert Delete GetRandom O(1)
    • Same Tree
    • Friends Within Three Jumps
    • Isomorphic Strings
    • Sum of Square Numbers
    • Valid Perfect Square
    • Evaluate Reverse Polish Notation
    • House Robber
    • Palindromic Substrings
    • Find Largest Value in Each Tree Row
    • Can Place Flowers
    • Insert Interval
    • Maximum Depth of Binary Tree
    • Two Sum
    • Paint House II
    • Max Points on a Line
    • Word Ladder II
    • Word Ladder
    • Validate IP Address
    • Maximum Product Subarray
    • Factor Combinations
    • Flatten Nested List Iterator
    • Max Stack
    • Number of Connected Components in an Undirected Graph
    • Combination Sum II
    • Permutations II
    • Permutations
    • Climbing Stairs
    • Paint House
    • Closest Binary Search Tree Value
    • Closest Binary Search Tree Value II
    • Rotate String
    • Max Area of Island
    • Maximum Subarray
    • Serialize and Deserialize Binary Tree
    • Second Minimum Node In a Binary Tree
    • Lowest Common Ancestor of a Binary Tree
    • Lowest Common Ancestor of a Binary Search Tree
    • Symmetric Tree
    • Binary Tree Upside Down
    • Maximum Depth of Binary Tree
    • Find Leaves of Binary Tree
    • Number of Islands
    • Nested List Weight Sum II
    • Nested List Weight Sum
    • Merge Intervals
    • Valid Triangle Number
    • Find K Closest Elements
    • Find Smallest Letter Greater Than Target
    • Pow(x,n)
    • Search in Rotated Sorted Array II
    • Search in Rotated Sorted Array
    • Sqrt(x)
    • Intersection of Two Linked Lists
    • Binary Tree Level Order Traversal
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Shortest Word Distance II
  • Binary Search
    • Find K Closest Elements
    • Find Min In Rotated Sorted Array
    • Find Peak Element
    • First Bad Version
    • First Position Of Target
    • Guess Num Higer Or Lower
    • Last Position Of Target
    • Longest Increasing Subsequence
    • Russian Doll Envelopes
    • Search In Big Sorted Array
    • Search Insert Position
    • Single Number IV
    • pow(x,n)
    • sqrt
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Search for a Range
    • Intersection of Two Arrays
    • Count of Smaller Numbers After Self
  • Binary Tree
    • 107. Binary Tree Level Order Traversal II
    • Lowest Common Ancestor of a Binary Tree
    • Lowest Common Ancestor of a Binary Tree II
    • Lowest Common Ancestor III
    • preorder Traversal
    • Inorder traversal
    • Binary Tree Path
    • post Order traversal
    • Level Traversal
    • Serialize and Deserialize Binary Tree 07/25
    • Find Leaves of Binary Tree 07/25
    • Sum of Left Leaves 07/25
    • Recover Binary Search Tree 07/26
    • Check Full Binary Tree 07/26
    • Binary Tree Longest Consecutive Sequence07/26
    • Equal Tree Partition 07/27
    • Same Tree 07/27
    • Sum Root to Leaf Numbers 07/26
    • Binary Search Tree Iterator 07/28
    • Preorder morris traversal 07/29
    • inorder traversal morris 07/29
  • BFS
    • Search Graph Nodes 07/30
    • Is Graph Bipartite? 07/30
    • Walls and Gates 07/30
    • Clone Graph 07/30
    • Word Ladder 07/30
    • Topological Sorting 08/01
    • Course Schedule 08/03
    • Course Schedule II 08/04
  • DFS
    • Target Sum 08/06
    • Minimum Subtree 08/07
    • Word Search 08/07
    • Pacific Atlantic Water Flow 08/08
    • Matrix Water Injection 08/10
    • Maximum Subtree 08/10
  • Dynamic Programming
    • 931. Minimum Falling Path Sum
    • Unique Binary Search Trees
  • Linked List
    • Reverse Linked List
    • Linked List Cycle
    • Swap Nodes in Pairs
    • Odd Even Linked List
    • Merge k Sorted Lists
    • Partition List
    • Palindrome Linked List
    • Reorder List
    • Linked List Cycle II
    • Delete Node in a Linked List
    • Reverse Nodes in k-Group
    • Rotate List
    • Reverse Linked List II
  • Arrays
    • 189. Rotate Array
    • 80. Remove Duplicates from Sorted Array II
    • 26. Remove Duplicates from Sorted Array
    • 628. Maximum Product of Three Numbers
    • 48. Rotate Image
    • 289. Game of Life
    • 334. Increasing Triplet Subsequence
    • 11. Container With Most Water
    • 122.Best Time to Buy and Sell Stock II
    • 274. H-Index
    • 134. Gas Station
    • 118. Pascal's Triangle
    • Sort Colors
    • Remove Element
    • Merge sorted array
    • First Missing Positive
  • Strings
    • 93. Restore IP Addresses
    • 71. Simplify Path
    • 43. Multiply Strings
    • 606. Construct String from Binary Tree
    • 917. Reverse Only Letters
    • 929.Unique Email Addresses
    • Valid Anagram
    • Compare Strings
    • Anagrams
    • Longest Common Prefix
    • Implement strStr()
    • String to Integer (atoi)
Powered by GitBook
On this page
  1. LinkedIn

All O`one Data Structure

Implement a data structure supporting the following operations:

  1. Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.

  2. Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.

  3. GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".

  4. GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".

Challenge: Perform all these in O(1) time complexity.

有bug

class AllOne {
    
    private Map<String,Node> map;
    private DoubleLinkedList ddl;
    /** Initialize your data structure here. */
    public AllOne() {
        map = new HashMap<>();
        ddl = new DoubleLinkedList();
    }
    
    /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
    public void inc(String key) {
        System.out.println("inc");
        
        if(key == null || key.length() == 0)
            return;
        Node node = null;
        if(!map.containsKey(key)){
            //check ddl 中是否包含key
            if(ddl.head.next.val == 1){
                node = ddl.head.next;
                node.addString(key);
            }else{
                node = new Node(1);
                ddl.addAfterHead(node);
                node.addString(key);
            }
            map.put(key,node);
        }
        
        else{
            node = map.get(key);
            map.put(key,ddl.update(node,key));
        }
        
        //ddl.dump();
        ddl.printNode();
    }
    
    /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
    public void dec(String key) {
        System.out.println("dec");
        if(key == null || key.length() == 0)
            return;
        if(map.containsKey(key)){
            Node node = map.get(key);
            int val = node.val;
            Node newNode = ddl.decUpdate(node,key);
            
            if(val == 1){
                map.remove(key);
            }
            
            else{
                map.put(key,newNode);
            }
        }
        
        //ddl.dump();
        ddl.printNode();
        
    }
    
    /** Returns one of the keys with maximal value. */
    public String getMaxKey() {
        return ddl.getMax();
    }
    
    /** Returns one of the keys with Minimal value. */
    public String getMinKey(){
        return ddl.getMin();
    }
    
    
    
    class DoubleLinkedList{
        private Node head;
        private Node tail;
        
        public DoubleLinkedList(){
            this.head = new Node(-1);
            this.tail = new Node(-1);
            
            head.next = tail;
            head.prev = null;
            tail.next = null;
            tail.prev = head;
        }
        
        public void dump(){
            Node tmp = head.next;
            
            while(tmp != tail && tmp != null){
                System.out.print(tmp.val+" : ");
                
                for(String s : tmp.getList()){
                    System.out.print(s + "  ");
                }
                
                System.out.println();
                
                tmp = tmp.next;
            }
        }
        
        public void printNode(){
            Node tmp = head;
            
            while(tmp != null){
                System.out.print(tmp.val+" -> ");
                tmp = tmp.next;
            }
        }
        public Node decUpdate(Node node, String s){
            int curVal = node.val;
            
            if(curVal == 1){
                node.removeString(s);
                if(node.isEmpty()){
                    
                    remove(node);
                    return head;
                }
                return node;
                
            }
            else{
                if(node.prev.val == curVal - 1){
                    Node prevNode = node.prev;
                    
                    prevNode.addString(s);
                    node.removeString(s);
                    if(node.isEmpty()){
                        System.out.println("this node is empty, ready to remove");
                        remove(node);
                    }
                    
                    return prevNode;
                }
                    Node newNode = new Node(curVal - 1);
                    
                    newNode.next = node;
                    newNode.prev = node.prev;
                    
                    node.prev.next = newNode;
                    node.prev = newNode;
                    newNode.addString(s);
                    node.removeString(s);
                    if(node.isEmpty()){
                        remove(node);
                    }
                
                
                return newNode;
            }
        }
        
        
        public void addAfterHead(Node node){
            node.next = head.next;
            node.prev = head;
            head.next.prev = node;
            head.next = node;
            
            
        }
        
        public void remove(Node node){
            node.prev.next = node.next;
            node.next.prev = node.prev;
            node.next = null;
            node.prev = null;
        }
        
        public Node update(Node node,String s){
            int curVal = node.val;

            if(node.next.val == curVal + 1){
                node.removeString(s);
                node.next.addString(s);
                if(node.isEmpty()){
                    remove(node);
                    return null;
                }
                
            }else{
                Node newNode = new Node(curVal+1);
                
                newNode.addString(s);
                node.removeString(s);
                
                newNode.next = node.next;
                newNode.prev = node;
                node.next.prev = newNode;
                node.next = newNode;
                if(node.isEmpty()){
                    remove(node);
                    return newNode;
                }
                
            }
            
            return node.next;
        }
        
        
        public String getMax(){
            if(tail.prev == head){
                return "";
            }
            
            List<String> list = tail.prev.getList();
            
            
            int size = tail.prev.listSize();
            
            
            return list.isEmpty() ? "": list.get(size -1);
        }
        
        public String getMin(){
            if(head.next == tail){
                return "";
            }
            
            List<String> list = head.next.getList();
            int size = head.next.listSize();
            return list.isEmpty() ? "": list.get(size -1);
        }
        
    }
    
    class Node{
        public int val;
        // store keys with same value
        public List<String> list;
        //store keys and it's index mapping
        public Map<String, Integer> map;
            
        //connect next and previous node 
        public Node next;
        public Node prev;
        
        public Node(int val){
            this.val = val;
            list = new ArrayList<>();
            map = new HashMap<>();
            next = null;
            prev = null;
        }
        
        public void addString(String s){
            list.add(s);
            map.put(s,list.size()-1);
        }
        
        public boolean removeString(String s){
            if(!map.containsKey(s)){
                return false;
            }
            
            int indexOfS = map.get(s);
            
            if(indexOfS != list.size()-1){
                
                String last = list.get(list.size()-1);
                
                list.set(indexOfS,last);
                map.put(last,indexOfS);
            }
            
            map.remove(s);
            list.remove(list.size()-1);
            
            return true;
        } 
        
        public boolean isEmpty(){
            return list.isEmpty();
        }
        
        public int listSize(){
            return list.size();
        }
        
        public List<String> getList(){
            return list;
        }
        
    }
}

/**
 * Your AllOne object will be instantiated and called as such:
 * AllOne obj = new AllOne();
 * obj.inc(key);
 * obj.dec(key);
 * String param_3 = obj.getMaxKey();
 * String param_4 = obj.getMinKey();
 */
PreviousValidate Binary Search TreeNextTop K Frequent Elements

Last updated 6 years ago