如何合并数组中连续重复的元素?
问题描述:
我需要合并数组中连续重复的元素,这样
I need to merge consecutive repeating elements in an array, such that
[1, 2, 2, 3, 1]
变成
[1, 2, 3, 1]
#uniq
不适用于此目的.为什么?因为 #uniq
会产生这个:
#uniq
doesn't work for this purpose. Why? Because #uniq
will produce this:
[1, 2, 3]
答
def remove_consecutive_duplicates(xs)
[xs.first] + xs.each_cons(2).select do |x,y|
x != y
end.map(&:last)
end
remove_consecutive_duplicates([1, 2, 2, 3, 1])
#=> [1,2,3,1]
这会返回一个新数组,就像 uniq
在 O(n)
时间内所做的和工作一样.
This returns a new array like uniq
does and works in O(n)
time.