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

Max Stack

犯错:popMax的时候 没有把对应的node从map里删除

时间复杂度 o(logn)

Design a max stack that supports push, pop, top, peekMax and popMax.

  1. push(x) -- Push element x onto stack.

  2. pop() -- Remove the element on top of the stack and return it.

  3. top() -- Get the element on the top.

  4. peekMax() -- Retrieve the maximum element in the stack.

  5. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.

Example 1:

MaxStack stack = new MaxStack();
stack.push(5); 
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5

Note:

  1. -1e7 <= x <= 1e7

  2. Number of operations won't exceed 10000.

  3. The last four operations won't be called when stack is empty.

这道题一般stack的地方用double linked list 维护 求max的地方,用map维护,key是值,value是node的list,因为存在可能相同的数值被加进stack里, 因为treemap可以给key排序,所有pop max的时候 直接从map最后一个取就好了

time O(logn) space o(n);

TreeMap:

  • For operations like add, remove, containsKey, time complexity is O(log n where n is number of elements present in TreeMap.

  • TreeMap always keeps the elements in a sorted(increasing) order, while the elements in a HashMap have no order. TreeMap also provides some cool methods for first, last, floor and ceiling of keys.

HashMap:

  • Complexity: get/put/containsKey() operations are O(1) in average case but we can’t guarantee that since it all depends on how much time does it take to compute the hash.

时间复杂度 peek 是o(1),其他是o(logn)

class MaxStack {

    /** initialize your data structure here. */
    
    private DoubleLinkedList ddl;
    private TreeMap<Integer, List<Node>> map;
    public MaxStack() {
        ddl = new DoubleLinkedList();
        map = new TreeMap<>();
    }
    
    public void push(int x) {
        
        Node node = new Node(x);
        ddl.add(node);
        if(!map.containsKey(x)){
            
            List<Node> tmp = new ArrayList<>();
            tmp.add(node);
            map.put(x,tmp);
        }else{
            map.get(x).add(node);
        }
        
        
    }
    
    public int pop() {
        int val = ddl.pop();
        
        //从map中删除
        
        map.get(val).remove(map.get(val).size()-1);
        
        if(map.get(val).isEmpty())
            map.remove(val);
        
        return val;
    }
    
    public int top() {
        return ddl.peek();
    }
    
    public int peekMax() {
        return map.lastKey();
    }
    
    public int popMax() {
        
        List<Node> list = map.get(map.lastKey());
        
        Node node =  list.remove(list.size()-1);
        
        ddl.remove(node);
        
        if(list.isEmpty()){
            map.remove(map.lastKey());
        }
        
        return node.val;
        
    }
    
}



class DoubleLinkedList{
    Node head = null;
    Node tail = null;
        
    public DoubleLinkedList(){
            head = new Node(-1);
            tail = new Node(-1);
            head.next = tail;
            head.prev = null;
            
            tail.next = null;
            tail.prev = head;
    }
    
    public int add(Node node){
       
    
        node.next = tail;
        node.prev = tail.prev;
        tail.prev.next = node;
        tail.prev = node;
        
        return node.val;
        
    }
    
    public int peek(){
        return tail.prev.val;
    }
    
    
    public int pop(){
        Node t = tail.prev;
        
        tail.prev = t.prev;
        
        t.prev.next = t.next;
        t.next = null;
        t.prev = null;
        
        return t.val;
    }
    
    public int remove(Node node){
       System.out.println(node.prev.val);
        node.next.prev = node.prev;
        node.prev.next = node.next;
        
        node.next = null;
        node.prev = null;
        
        return node.val;
    }
        
}

class Node{
        
        public Node next;
        public Node prev;
        public int val;
        public Node(int x){
            this.val = x;
            next = null;
            prev = null;
        }
}

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */

双stack,popMax是o(n),其他是o(1)

class MaxStack {
    private Stack<Integer> stack = null;
    private Stack<Integer> maxStack = null;
    
    /** initialize your data structure here. */
    public MaxStack() {
        stack = new Stack<>();
        maxStack = new Stack<>();
    }
    
    public void push(int x) {
        int max = maxStack.isEmpty() ? x : maxStack.peek();
        
        if(max > x ){
            maxStack.push(max);
        }else{
            maxStack.push(x);
        }
        
        stack.push(x);
    }
    
    public int pop() {
        maxStack.pop();
        return stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int peekMax() {
        return maxStack.peek();
    }
    
    public int popMax() {
        int max = maxStack.peek();
        
        Stack<Integer> tmpStack = new Stack<>();
        
        while(max != stack.peek()) {
            tmpStack.push(pop());
        }
        
        pop();
        
        while(!tmpStack.isEmpty()){
            push(tmpStack.pop());
        }
        
        return max;
    }
}

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */
PreviousFlatten Nested List IteratorNextNumber of Connected Components in an Undirected Graph

Last updated 6 years ago

Max Stack - LeetCodeLeetCode
Logo