문제: 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
}
}
'알고리즘' 카테고리의 다른 글
[Swift] LeetCode - 200. Number of Islands (0) | 2022.02.16 |
---|---|
[Swift] LeetCode - 3. Longest Substring Without Repeating Characters (0) | 2022.02.16 |
[Swift] LeetCode - 20. Valid Parentheses (0) | 2022.02.15 |
[Swift] LeetCode - 2. Add Two Numbers (0) | 2022.02.15 |
[Swift] LeetCode - 49. Group Anagrams (0) | 2022.02.14 |
댓글