红宝石镶嵌的优点 [英] Advantages of Set in ruby

查看:76
本文介绍了红宝石镶嵌的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Set 的主要优点似乎是保留了独特的元素。但这可以在 Array 中轻松实现,

The main advantage of Set seems to be maintaining unique elements. But that can be easily achieved in Array with,

array = [2,3,4]
array | [2,5,6] # => [2,3,4,5,6]

唯一的独特功能(可能仅适用于少数用例)

The only distinct feature (which could apply to few use-cases) I came across was,

set1 = [1,2,3].to_set
set2 = [2,1,3].to_set
set1 == set2 # => true
[1,2,3] == [2,1,3] # => false

由于 Array 具有各种功能和操作与之相关联,何时以及为什么我应该使用 Set

Since Array has various functions and operations associated with it, when and why should I use Set?

有很多链接可以比较 Array Set 但是我还没有遇到 Set 的重要应用。

There are many links that compare Array and Set but I haven't come across significant application of Set.

推荐答案

当然,无论您使用 Set 做什么,都有一种使用 Array 的方法。使用 Set 的优点是,由于它是基于 Hash 实现的,因此对其的大多数操作都是O( 1)使用 Array 时的复杂度可以为O(n)。

Sure, whatever you can do with Set, there is a way to do it with Array. The advantage of using a Set is that, since it is implemented based on Hash, most operations on it are O(1) complexity, while doing it with Array can be O(n).

示例为:

Set.new([1, 2, 3]).include?(2) # O(1) complexity
[1, 2, 3].include?(2) # O(n) complexity

这篇关于红宝石镶嵌的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆