ac solution code


  • 0
    /*
     SWIFT
     Solution1. space = O(n); time:
     push: O(1)
     pop: O(1)
     peek: O(1)
    
     Queue: stack2 + stack1
     Stack1: Push(IN) interface
     Stack2: Pop(OUT) interface (Transit stack, used to reverse the order of stack1 to satisfy FIFO)
    
     STEPS:
     e.g. push 1...4
    
     1. Push    
        Push elements to stack1:  4...1 (top to bottom)
     2. pop/peek
        1) Reverse: If stack2 isEmpty, reverse stack1 to stack2: 1...4 (top to bottom)
        2) Then pop top of stack2
     
     Keep going accordingly with the above steps if new element push/pop/peek to queue.
     */
    public class MyQueue {
        fileprivate var stack1 = Stack<Int>()
        fileprivate var stack2 = Stack<Int>()
        init() {}
        fileprivate func stack1ToStack2() {
            if stack2.isEmpty() {
                while !stack1.isEmpty() {
                    stack2.push(stack1.pop()!)
                }
            }
        }
    
        // Push element x to the back of queue.
        public func push(_ x: Int) {
            stack1.push(x)
        }
    
        // Removes the element from in front of queue.
        public func pop() -> Int? {
            stack1ToStack2()
            return stack2.pop()
        }
    
        // Get the front element.
        public func peek() -> Int? {
            stack1ToStack2()
            return stack2.peek()
        }
    
        // Return whether the queue is empty.
        public func empty() -> Bool {
            return stack1.isEmpty() && stack2.isEmpty();
        }
    }
    

    0_1484957908961_Evernote Camera Roll 20170120 155903.jpg


Log in to reply
 

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