μ°μ μμ νλ μμκ° μ½μ λ λλ§λ€ μ°μ μμμ λ°λΌ μ λ ¬λλ©°, κ°μ₯ λμ μ°μ μμμ μμκ° λ¨Όμ μ²λ¦¬λ©λλ€.
μ΄μ μ ꡬνν Heapμ μ¬μ©νμ¬ μ°μ μμ νλ₯Ό μ½κ² ꡬνν μ μμ΅λλ€.
μλλ PriorityQueue ꡬ쑰체λ₯Ό μ λ€λ¦μΌλ‘ μ μν μ½λμ λλ€.
struct PriorityQueue<T> {
private var heap: Heap<T>
var isEmpty: Bool {
return heap.isEmpty
}
var count: Int {
return heap.count
}
var peek: T? {
return heap.peek
}
init(sort: @escaping (T, T) -> Bool) {
heap = Heap(priorityFunction: sort)
}
mutating func enqueue(_ element: T) {
heap.push(element)
}
mutating func dequeue() -> T? {
return heap.pop()
}
}
μ μ½λμμλ μ°μ μμ νμ κΈ°λ³Έ λμμ ꡬννμ΅λλ€.
- enqueue(_:): μ°μ μμ νμ μ μμλ₯Ό μΆκ°ν©λλ€. μκ° λ³΅μ‘λλ O(log n)μ λλ€.
- dequeue(): κ°μ₯ λμ μ°μ μμμ μμλ₯Ό μ κ±°νκ³ λ°νν©λλ€. μκ° λ³΅μ‘λλ O(log n)μ λλ€.
μ°μ μμ νλ μ΅μ μ°μ μμ νμ μ΅λ μ°μ μμ νλ‘ λλ μ μμ΅λλ€.
μ΅μ μ°μ μμ νλ μ«μκ° μμμλ‘ μ°μ μμκ° λκ³ , μ΅λ μ°μ μμ νλ μ«μκ° ν΄μλ‘ μ°μ μμκ° λμ΅λλ€.
μ΅μ μ°μ μμ ν
var priorityQueue = PriorityQueue<Int>(sort: <)
// μμ μ½μ
priorityQueue.enqueue(5)
priorityQueue.enqueue(1)
priorityQueue.enqueue(3)
priorityQueue.enqueue(2)
// κ°μ₯ μ°μ μμκ° λμ μμ(μ΅μκ°) νμΈ
print(priorityQueue.peek!) // 1
// μμ μ κ±°
print(priorityQueue.dequeue()!) // 1
print(priorityQueue.dequeue()!) // 2
print(priorityQueue.dequeue()!) // 3
print(priorityQueue.dequeue()!) // 5
μ΅λ μ°μ μμ ν
var maxPriorityQueue = PriorityQueue<Int>(sort: >)
maxPriorityQueue.enqueue(5)
maxPriorityQueue.enqueue(1)
maxPriorityQueue.enqueue(3)
maxPriorityQueue.enqueue(2)
// κ°μ₯ μ°μ μμκ° λμ μμ(μ΅λκ°) νμΈ
print(maxPriorityQueue.peek!) // 5
// μμ μ κ±°
print(maxPriorityQueue.dequeue()!) // 5
print(maxPriorityQueue.dequeue()!) // 3
print(maxPriorityQueue.dequeue()!) // 2
print(maxPriorityQueue.dequeue()!) // 1
PriorityQueueλ λ΄λΆμ μΌλ‘ Heapμ μ¬μ©νμ¬ ν¨μ¨μ μΌλ‘ μμλ₯Ό μ½μ (enqueue)νκ³ μ κ±°(dequeue)ν©λλ€.
sort λ§€κ°λ³μμ λ°λΌ μ΅μ μ°μ μμ νλ‘ λμν μλ μκ³ , μ΅λ μ°μ μμ νλ‘ λμν μλ μμ΅λλ€.
μκ° λ³΅μ‘λλ enqueueμ dequeue λͺ¨λ O(log n)μ λλ€.
'β¨οΈ Language > swift' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[Swift] ν(Heap) ꡬννκΈ° (0) | 2024.09.27 |
---|---|
[Swift] Dequeue ꡬννκΈ° (0) | 2024.09.27 |
[Swfit] ν(Queue) ꡬννκΈ° (1) | 2024.09.27 |
[Swift] μ€ν(Stack) ꡬννκΈ° (0) | 2024.09.27 |
[Swift] μλ μ°Έμ‘° μΉ΄μ΄νΈ (0) | 2024.04.02 |