Java beats 93% using self-design double linklist with extra field min. Simple and easy


  • 0
    M

    The idea is simple. Just document the min from start to that node and
    when needed to return min, return that node's min.

    class ListNode{
        ListNode next,prev;
        int val;
        int min;
        public ListNode(int x){val=x;}
    }
    public class MinStack {
        ListNode pointer,head;
        /** initialize your data structure here. */
        public MinStack() {
            head=new ListNode(0);
            head.min=Integer.MAX_VALUE;
            pointer=head;
        }
        
        public void push(int x) {
            pointer.next=new ListNode(x);
            pointer.next.prev=pointer;
            pointer.next.min=Math.min(pointer.min,pointer.next.val);
            pointer=pointer.next;
        }
        
        public void pop() {
            if(pointer!=head){
                pointer=pointer.prev;
                pointer.next=null;
            }
            
        }
        
        public int top() {
            return pointer.val;
        }
        
        public int getMin() {
            return pointer.min;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.