Further modifications that beats 84% java solutions :


  • 0
    G

    Re: Sharing My Java Solution (Beats 65%)

    class MyQueue {
    
        Stack<Integer> curStack = new Stack<>();
        Stack<Integer> tempStack = new Stack<>();
        int peek;
        
         // Push element x to the back of queue.   
        public void push(int x) {
            curStack.push(x);
            if (curStack.size()==1){
                peek = x;
            }
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            while(curStack.size()>0){
                tempStack.push(curStack.pop());
            }
            tempStack.pop();
            while(tempStack.size()>0){
                curStack.push(tempStack.pop());
                if(curStack.size()==1){
                    peek = curStack.peek();
                }
            }
        }
    
        // Get the front element.
        public int peek() {
            return peek;
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return curStack.size()==0;
        }
    }
    

Log in to reply
 

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