코딩 테스트 연습 - Implement Queue using Stacks

다용도리모콘·2020년 10월 8일
0

CodingTest

목록 보기
27/34

01. 이해

큐에서 제공하는 함수들을 가지고 스택의 내부 함수를 구현

02. 계획

push에서 queue처럼 작동하도록 미리 넣어두거나, pop할 때 queue처럼 빼지도록 해야하는데 peek을 간단히 구현하기 위해서는 넣을 때 제대로 넣어두는게 좋을 듯.

03. 실행

/**
 * Runtime: 152 ms, faster than 83.72% of Kotlin online submissions for Implement Queue using Stacks.
 * Memory Usage: 34.8 MB, less than 25.58% of Kotlin online submissions for Implement Queue using Stacks.
 */
class MyQueue() {

    /** Initialize your data structure here. */
    var stack = ArrayList<Int>()
    val tempStack = ArrayList<Int>()

    /** Push element x to the back of queue. */
    fun push(x: Int) {
        if (stack.isEmpty()){
            stack.add(x)
        }else {
            for (i in 0 until stack.size) {
                tempStack.add(stack.removeAt(stack.size -1))
            }
            stack.add(x)
            while (tempStack.isNotEmpty()){
                stack.add(tempStack.removeAt(tempStack.size - 1))
            }
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    fun pop(): Int {
        return stack.removeAt(stack.size - 1)
    }

    /** Get the front element. */
    fun peek(): Int {
        return stack.last()
    }

    /** Returns whether the queue is empty. */
    fun empty(): Boolean {
        return stack.isEmpty()
    }

}


/**
 * Runtime: 172 ms, faster than 25.58% of Kotlin online submissions for Implement Queue using Stacks.
 * Memory Usage: 34.8 MB, less than 20.93% of Kotlin online submissions for Implement Queue using Stacks.
 */
class MyQueue2() {

    /** Initialize your data structure here. */
    val stack1 = ArrayList<Int>()
    val stack2 = ArrayList<Int>()
    var front = 0

    /** Push element x to the back of queue. */
    fun push(x: Int) {
        if (stack1.isEmpty()){
            front = x
        }
        stack1.add(x)
    }

    /** Removes the element from in front of queue and returns that element. */
    fun pop(): Int {
        if (stack2.isEmpty()){
            while (stack1.isNotEmpty()){
                stack2.add(stack1.removeAt(stack1.size - 1))
            }
        }
        return stack2.removeAt(stack2.size - 1)
    }

    /** Get the front element. */
    fun peek(): Int {
        if (stack2.isNotEmpty()){
            return stack2.last()
        }
        return front
    }

    /** Returns whether the queue is empty. */
    fun empty(): Boolean {
        return stack1.isEmpty() && stack2.isEmpty()
    }

}

04. 회고

큐로 스택을 만드는 문제와 유사한 유형이었다. 메모리 성적이 좋지 않게 나오는건 arraylist를 사용해서일까?

Runtime: 164 ms, faster than 46.51% of Kotlin online submissions for Implement Queue using Stacks.
Memory Usage: 34.9 MB, less than 9.30% of Kotlin online submissions for Implement Queue using Stacks.

0개의 댓글