JAVA solution two stack ,80% beats


  • -1
    H
    class MyQueue {
        private Stack<Integer> in =new Stack<Integer>();
        private Stack<Integer> out =new Stack<Integer>();
        // Push element x to the back of queue.
        public void push(int x) {
              in.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
             makeOut();
             out.pop();
        }
    
        // Get the front element.
        public int peek() {
             makeOut();
             return out.peek();
        }
        
        private void makeOut(){
            if(out.empty()){
                while(!in.empty()){
                    out.push(in.pop());
                }
            }
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
             return in.empty()&&out.empty();
        }
    }
    

    hope u guys like it


  • 0
    L

    May I ask how long does your solution take?
    I use the same solution,but it takes 110ms and only beats 40%


  • 0

    Is this correct? Once the elements goes to "out" they never come back! Suppose you have a stack in "in" then you pop(), all the elements are transferred to "out". If you then push(), the new element will be the only one in the "in" since you didn't return them from "out" to "in", so this new element is actually in the front (when you do the next pop() this will be pop out).


  • 0
    H

    e...
    peek and pop,will do on "out",and if out is not empty ,whatever in "in" doesn't matter,
    normal stack will push on top and peek or pop on top soit will always be the right bottom up order in out for example
    like u push 1,2,3 and peek ,in 3,2,1 out null-》 in null out 1,2,3 peek get 1,right?
    push 1, in 1 out 1,2,3
    and pop, in 1 out 2,3
    //pop util out is empty
    and then pop it will transfer in to out line in 1 out null-> in null out 1
    the final is 1,2,3,1


Log in to reply
 

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