Files
Yudong Jin 2778a6f9c7 Translate all code to English (#1836)
* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
2025-12-31 07:44:52 +08:00

65 lines
1.4 KiB
Ruby

=begin
File: top_k.rb
Created Time: 2024-04-19
Author: Blue Bean (lonnnnnnner@gmail.com)
=end
require_relative "./my_heap"
### Push element to heap ###
def push_min_heap(heap, val)
# Negate element
heap.push(-val)
end
### Pop element from heap ###
def pop_min_heap(heap)
# Negate element
-heap.pop
end
### Access heap top element ###
def peek_min_heap(heap)
# Negate element
-heap.peek
end
### Get elements from heap ###
def get_min_heap(heap)
# Negate all elements in heap
heap.max_heap.map { |x| -x }
end
### Find largest k elements in array using heap ###
def top_k_heap(nums, k)
# Python's heapq module implements min heap by default
# Note: We negate all heap elements to simulate min heap using max heap
max_heap = MaxHeap.new([])
# Enter the first k elements of array into heap
for i in 0...k
push_min_heap(max_heap, nums[i])
end
# Starting from the (k+1)th element, maintain heap length as k
for i in k...nums.length
# If current element is greater than top element, top element exits heap, current element enters heap
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
### Driver Code ###
if __FILE__ == $0
nums = [1, 7, 6, 3, 2]
k = 3
res = top_k_heap(nums, k)
puts "The largest #{k} elements are"
print_heap(res)
end