The error is occurring because the compiler does not recognize the "Heap" class. In Swift, there is no built-in heap data structure. You can implement a heap yourself or use a library that provides a heap implementation.

Here's an example implementation of a min-heap using an array:

struct Heap<T> {
    private var elements: [T]
    private let priorityFunction: (T, T) -> Bool
    
    init(_ elements: [T], _ priorityFunction: @escaping (T, T) -> Bool) {
        self.elements = elements
        self.priorityFunction = priorityFunction
        buildHeap()
    }
    
    private mutating func buildHeap() {
        for i in (0..<count/2).reversed() {
            siftDown(i)
        }
    }
    
    private mutating func siftDown(_ index: Int) {
        var parent = index
        while true {
            let leftChild = 2 * parent + 1
            let rightChild = leftChild + 1
            var swapIndex = parent
            
            if leftChild < count && priorityFunction(elements[leftChild], elements[swapIndex]) {
                swapIndex = leftChild
            }
            
            if rightChild < count && priorityFunction(elements[rightChild], elements[swapIndex]) {
                swapIndex = rightChild
            }
            
            if swapIndex == parent {
                return
            }
            
            elements.swapAt(parent, swapIndex)
            parent = swapIndex
        }
    }
    
    private mutating func siftUp(_ index: Int) {
        var child = index
        var parent = (child - 1) / 2
        
        while child > 0 && priorityFunction(elements[child], elements[parent]) {
            elements.swapAt(child, parent)
            child = parent
            parent = (child - 1) / 2
        }
    }
    
    mutating func insert(_ element: T) {
        elements.append(element)
        siftUp(count - 1)
    }
    
    mutating func remove() -> T? {
        guard !isEmpty else {
            return nil
        }
        
        elements.swapAt(0, count - 1)
        let removedElement = elements.removeLast()
        siftDown(0)
        return removedElement
    }
    
    var count: Int {
        return elements.count
    }
    
    var isEmpty: Bool {
        return elements.isEmpty
    }
    
    func peek() -> T? {
        return elements.first
    }
}

Once you have the heap implementation, you can use it in your halveArray function:

class Solution {
    func halveArray(_ nums: [Int]) -> Int {
        var heap = Heap(nums, >)
        var sum = nums.reduce(0, +)
        var count = 0
        while sum > heap.peek()! {
            sum -= heap.remove()!
            count += 1
        }
        return count
    }
}
``
class Solution func halveArray_ nums Int - Int var heap = Heapnums var sum = numsreduce0 + var count = 0 while sum heappeek! sum -= heapremove!

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

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