Algorithm/PTUStudy

10주차. 데크, 우선순위 큐(원형 데크 디자인)

지구우중 2023. 3. 30. 19:13

26. 원형 데크 디자인

https://leetcode.com/problems/design-circular-deque/

 

Design Circular Deque - LeetCode

Can you solve this real interview question? Design Circular Deque - Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class: * MyCircularDeque(int k) Initializes the deque with a maximum size of k. * boole

leetcode.com

📌문제
다음 연산을 제공하는 원형 데크를 디자인하라.



- 예제1
  📝입력

["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]



  💻출력

[null, true, true, true, false, 2, true, true, true, 4]

    
📌풀이

5ms, 43.2mb

class MyCircularDeque {
    int maxSize, head = 0, tail = -1;
    int[] data;
    public MyCircularDeque(int k) {
        data = new int[k];
        maxSize = k;
    }

    public boolean insertFront(int value) {
        if(isFull()) return false;
        head = --head < 0 ? maxSize-1 : head % maxSize;
        data[head] = value;
        if(tail == -1) tail = head;
        return true;
    }

    public boolean insertLast(int value) {
        if(isFull()) return false;
        tail = ++tail % maxSize;
        data[tail] = value;
        return true;
    }

    public boolean deleteFront() {
        if(isEmpty()) return false;
        if(head == tail){
            head = 0;
            tail = -1;
        }
        else head = ++head % maxSize;
        return true;
    }

    public boolean deleteLast() {
        if(isEmpty()) return false;
        if(head == tail){
            head = 0;
            tail = -1;
        }
        else tail = --tail < 0 ? maxSize-1 : tail % maxSize;
        return true;
    }

    public int getFront() {
        return isEmpty() ? -1 : data[head];
    }

    public int getRear() {
        return isEmpty() ? -1 : data[tail];
    }

    public boolean isEmpty() {
        return tail == -1 && head == 0;
    }

    public boolean isFull() {
        return !isEmpty() && (tail + 1) % maxSize == head;
    }
}

 

전에 풀었던 원형 큐 디자인 부분에서, head부분을 -- 시켜 앞과 뒤쪽으로 데이터 삽입이 가능하도록 만들었다.