class Solution { func halveArray(_ nums: [Int]) -> Int { var pq = PriorityQueue() for num in nums { pq.push(Double(num)) } var res = 0 var sum = nums.reduce(0, +) var sum2 = 0.0 while sum2 < Double(sum) / 2 { let x = pq.top()! pq.pop() sum2 += x / 2 pq.push(x / 2) res += 1 } return res } }

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
    }
}
class Solution public int halveArrayvectorint& nums priority_queuedouble pqnumsbegin numsend; int res = 0; double sum = accumulatenumsbegin numsend 00 sum2 = 00; while

原文地址: https://www.cveoy.top/t/topic/iigd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录