Remove from the array elements that are repeated

后端 未结 5 1181
执念已碎
执念已碎 2020-12-12 01:37

What is the best way to remove from the array elements that are repeated. For example, from the array

a = [4, 3, 3, 1, 6, 6]

need to get

5条回答
  •  隐瞒了意图╮
    2020-12-12 02:11

    a = [4, 3, 3, 1, 6, 6]
    a.select{|b| a.count(b) == 1}
    #=> [4, 1]
    

    More complicated but faster solution (O(n) I believe :))

    a = [4, 3, 3, 1, 6, 6]
    ar = []
    add = proc{|to, form| to << from[1] if form.uniq.size == from.size }
    a.sort!.each_cons(3){|b| add.call(ar, b)}
    ar << a[0] if a[0] != a[1]; ar << a[-1] if a[-1] != a[-2]
    

提交回复
热议问题