This commit is contained in:
krahets
2024-04-28 22:35:59 +08:00
parent f986ae3c8c
commit f748af6aa4
34 changed files with 588 additions and 136 deletions
+22 -1
View File
@@ -437,7 +437,28 @@ comments: true
=== "Ruby"
```ruby title="top_k.rb"
[class]{}-[func]{top_k_heap}
### 基於堆積查詢陣列中最大的 k 個元素 ###
def top_k_heap(nums, k)
# 初始化小頂堆積
# 請注意:我們將堆積中所有元素取反,從而用大頂堆積來模擬小頂堆積
max_heap = MaxHeap.new([])
# 將陣列的前 k 個元素入堆積
for i in 0...k
push_min_heap(max_heap, nums[i])
end
# 從第 k+1 個元素開始,保持堆積的長度為 k
for i in k...nums.length
# 若當前元素大於堆積頂元素,則將堆積頂元素出堆積、當前元素入堆積
if nums[i] > peek_min_heap(max_heap)
pop_min_heap(max_heap)
push_min_heap(max_heap, nums[i])
end
end
get_min_heap(max_heap)
end
```
=== "Zig"