class Solution public int halveArrayvectorint& nums priority_queuedouble pqnumsbegin numsend; int res = 0; double sum = accumulatenumsbegin numsend 00 sum2 = 00; while
class Solution {
func halveArray(_ nums: [Int]) -> Int {
var pq = PriorityQueue
struct PriorityQueue<T: Comparable> { private var heap = T
var isEmpty: Bool {
return heap.isEmpty
}
var count: Int {
return heap.count
}
mutating func push(_ element: T) {
heap.append(element)
siftUp(count - 1)
}
mutating func pop() -> T? {
if isEmpty {
return nil
}
heap.swapAt(0, count - 1)
let element = heap.removeLast()
siftDown(0)
return element
}
func top() -> T? {
return heap.first
}
private mutating func siftUp(_ index: Int) {
var child = index
var parent = (child - 1) / 2
while child > 0 && heap[child] > heap[parent] {
heap.swapAt(child, parent)
child = parent
parent = (child - 1) / 2
}
}
private mutating func siftDown(_ index: Int) {
var parent = index
while true {
var maxChild = parent
let leftChild = parent * 2 + 1
let rightChild = parent * 2 + 2
if leftChild < count && heap[leftChild] > heap[maxChild] {
maxChild = leftChild
}
if rightChild < count && heap[rightChild] > heap[maxChild] {
maxChild = rightChild
}
if maxChild == parent {
break
}
heap.swapAt(parent, maxChild)
parent = maxChild
}
}
原文地址: https://www.cveoy.top/t/topic/iigd 著作权归作者所有。请勿转载和采集!