This commit is contained in:
krahets
2024-05-31 12:45:17 +08:00
parent 6bac0db1c4
commit 124c7ce24d
27 changed files with 1003 additions and 146 deletions
+9 -1
View File
@@ -311,7 +311,15 @@ comments: true
=== "Ruby"
```ruby title="my_heap.rb"
[class]{MaxHeap}-[func]{__init__}
### 构造方法,根据输入列表建堆 ###
def initialize(nums)
# 将列表元素原封不动添加进堆
@max_heap = nums
# 堆化除叶节点以外的其他所有节点
parent(size - 1).downto(0) do |i|
sift_down(i)
end
end
```
=== "Zig"
+14 -14
View File
@@ -132,17 +132,17 @@ comments: true
Queue<Integer> minHeap = new PriorityQueue<>();
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
/* 元素入堆 */
maxHeap.offer(1);
maxHeap.offer(3);
maxHeap.offer(2);
maxHeap.offer(5);
maxHeap.offer(4);
/* 获取堆顶元素 */
int peek = maxHeap.peek(); // 5
/* 堆顶元素出堆 */
// 出堆元素会形成一个从大到小的序列
peek = maxHeap.poll(); // 5
@@ -150,13 +150,13 @@ comments: true
peek = maxHeap.poll(); // 3
peek = maxHeap.poll(); // 2
peek = maxHeap.poll(); // 1
/* 获取堆大小 */
int size = maxHeap.size();
/* 判断堆是否为空 */
boolean isEmpty = maxHeap.isEmpty();
/* 输入列表并建堆 */
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
```
@@ -347,7 +347,7 @@ comments: true
max_heap.push(2);
max_heap.push(5);
max_heap.push(4);
/* 获取堆顶元素 */
let peek = max_heap.peek().unwrap(); // 5
@@ -383,17 +383,17 @@ comments: true
var minHeap = PriorityQueue<Int>()
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
val maxHeap = PriorityQueue { a: Int, b: Int -> b - a }
/* 元素入堆 */
maxHeap.offer(1)
maxHeap.offer(3)
maxHeap.offer(2)
maxHeap.offer(5)
maxHeap.offer(4)
/* 获取堆顶元素 */
var peek = maxHeap.peek() // 5
/* 堆顶元素出堆 */
// 出堆元素会形成一个从大到小的序列
peek = maxHeap.poll() // 5
@@ -401,13 +401,13 @@ comments: true
peek = maxHeap.poll() // 3
peek = maxHeap.poll() // 2
peek = maxHeap.poll() // 1
/* 获取堆大小 */
val size = maxHeap.size
/* 判断堆是否为空 */
val isEmpty = maxHeap.isEmpty()
/* 输入列表并建堆 */
minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4))
```
@@ -415,7 +415,7 @@ comments: true
=== "Ruby"
```ruby title="heap.rb"
# Ruby 未提供内置 Heap 类
```
=== "Zig"