본문 바로가기
알고리즘

[Swift] LeetCode - 641. Design Circular Deque

by 고고 2022. 2. 16.

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

 

Design Circular Deque - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

rear는 한 칸 뒤를 가리킵니다.

class MyCircularDeque {
    var front: Int = 0
    var rear: Int = 0
    var queue: [Int?]
    let capacity: Int

    init(_ k: Int) {
        self.queue = Array(repeating: nil, count: k)
        self.capacity = k
    }
    
    func insertFront(_ value: Int) -> Bool {
        if queue[(front - 1 + capacity) % capacity] == nil {
            front = (front - 1 + capacity) % capacity
            queue[front] = value
            return true
        } else {
            return false
        }
    }
    
    func insertLast(_ value: Int) -> Bool {
        if queue[rear] == nil {
            queue[rear] = value
            rear = (rear + 1) % capacity
            return true
        } else {
            return false
        }
    }
    
    func deleteFront() -> Bool {
        if queue[front] == nil {
            return false
        } else {
            queue[front] = nil
            front = (front + 1) % capacity
            return true
        }
    }
    
    func deleteLast() -> Bool {
        if queue[(rear - 1 + capacity) % capacity] == nil {
            return false
        } else {
            rear = (rear - 1 + capacity) % capacity
            queue[rear] = nil
            return true
        }
    }
    
    func getFront() -> Int {
        return queue[front] ?? -1
    }
    
    func getRear() -> Int {
        return queue[(rear - 1 + capacity) % capacity] ?? -1
    }
    
    func isEmpty() -> Bool {
        return front == rear && queue[front] == nil
    }
    
    func isFull() -> Bool {
        return front == rear && queue[front] != nil
    }
}

댓글