从数组中删除重复的元素 [英] Remove from the array elements that are repeated
本文介绍了从数组中删除重复的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从数组中删除重复元素的最佳方法是什么.例如,从数组
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]
需要得到
a = [4, 1]
我的方法在处理大量元素时工作速度太慢.
My method works to too slowly with big amount of elements.
arr = [4, 3, 3, 1, 6, 6]
puts arr.join(" ")
nouniq = []
l = arr.length
uniq = nil
for i in 0..(l-1)
for j in 0..(l-1)
if (arr[j] == arr[i]) and ( i != j )
nouniq << arr[j]
end
end
end
arr = (arr - nouniq).compact
puts arr.join(" ")
推荐答案
a = [4, 3, 3, 1, 6, 6]
a.select{|b| a.count(b) == 1}
#=> [4, 1]
更复杂但更快的解决方案 (O(n)
我相信 :))
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]
这篇关于从数组中删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文