gpt4 book ai didi

ruby - 从 SortedSet 中检索最大元素

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:05 26 4
gpt4 key购买 nike

我找到了SortedSet#max,不过好像是O(N)。现在我会做这样的事情:

s = SortedSet.new((1..100000).to_a.reverse)

reverse 只是为了确定。

min_element = nil; s.each { |x| min_element = x; break }

对于最大元素,我将构建另一个 SortedSet,所有值都乘以 -1 并执行相同的操作。有没有更传统的方法来做到这一点?

最佳答案

猴子补丁 SortedSet

class SortedSet
def max
@keys[-1]
end

def min
@keys[0]
end
end

那是 O(1)。

关于ruby - 从 SortedSet 中检索最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44753142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com