2.4.19

2.4.19 #

解答 #

官方实现已经包含了这部分的代码,见:https://algs4.cs.princeton.edu/24pq/MaxPQ.java.html

相应的构造函数(Java)

public MaxPQ(Key[] keys) {
    n = keys.length;
    pq = (Key[]) new Object[keys.length + 1];
    for (int i = 0; i < n; i++)
        pq[i+1] = keys[i];
    for (int k = n/2; k >= 1; k--)
        sink(k);
    assert isMaxHeap();
}

代码 #

构造函数(C#)

/// <summary>
/// 从已有元素建立一个最大堆。(O(n))
/// </summary>
/// <param name="keys">已有元素。</param>
public MaxPQ(Key[] keys)
{
    _n = keys.Length;
    pq = new Key[keys.Length + 1];
    for (var i = 0; i < keys.Length; i++)
        pq[i + 1] = keys[i];
    for (var k = _n / 2; k >= 1; k--)
        Sink(k);
    Debug.Assert(IsMaxHeap());
}

另请参阅 #

PriorityQueue 库