ruby中Array#uniq方法的时间复杂度是多少?

时间:2013-01-07 17:00:33

标签: ruby

任何人都可以告诉我ruby内部使用哪种算法来使用Array#uniq方法从ruby数组中删除重复项?

5 个答案:

答案 0 :(得分:5)

来自docs

static VALUE
rb_ary_uniq(VALUE ary)
{
    VALUE hash, uniq, v;
    long i;

    if (RARRAY_LEN(ary) <= 1)
        return rb_ary_dup(ary);
    if (rb_block_given_p()) {
        hash = ary_make_hash_by(ary);
        uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
        st_foreach(RHASH_TBL(hash), push_value, uniq);
    }
    else {
        hash = ary_make_hash(ary);
        uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
        for (i=0; i<RARRAY_LEN(ary); i++) {
            st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
            if (st_delete(RHASH_TBL(hash), &vv, 0)) {
                rb_ary_push(uniq, v);
            }
        }
    }
    ary_recycle_hash(hash);

    return uniq;

它有O(N)复杂度

答案 1 :(得分:3)

分摊O(n)为uses Hash internally

答案 2 :(得分:3)

这取决于您正在谈论的 “内部”。目前使用的有7个生产就绪的Ruby实现,而Ruby语言规范没有规定任何特定的算法。所以,这实际上取决于实施。

例如,这是the implementation Rubinius uses

Rubinius.check_frozen

if block_given?
  im = Rubinius::IdentityMap.from(self, &block)
else
  im = Rubinius::IdentityMap.from(self)
end
return if im.size == size

array = im.to_array
@tuple = array.tuple
@start = array.start
@total = array.total

self

这是the one from JRuby

RubyHash hash = makeHash();
if (realLength == hash.size()) return makeShared();

RubyArray result = new RubyArray(context.runtime, getMetaClass(), hash.size()); 

int j = 0;
try {
    for (int i = 0; i < realLength; i++) {
        IRubyObject v = elt(i);
        if (hash.fastDelete(v)) result.values[j++] = v;
    }
} catch (ArrayIndexOutOfBoundsException aioob) {
    concurrentModification();
}
result.realLength = j;
return result;

答案 3 :(得分:1)

It compares elements using their hash (provided by the Object#hash method) then compares hashes with Object#eql?.

来源:https://github.com/ruby/ruby/blob/trunk/array.c#L3976

答案 4 :(得分:1)

时间复杂度是线性时间,即O(n),因为它使用Hash进行内部实现 算法