如何合并数组中的连续重复元素?

dan*_*dan 7 ruby

我需要合并一个数组中的连续重复元素

[1, 2, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)

变

[1, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)

#uniq不适用于此目的.为什么?因为#uniq会产生这个:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

tok*_*and 10

核心中有一个抽象,几乎就是这个工作,Enumerable#chunk:

xs = [1, 2, 2, 3, 3, 3, 1]
xs.chunk { |x| x }.map(&:first)
#=> [1, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)

  • 比公认的答案更短、更干净、更有效。 (2认同)

sep*_*p2k 7

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]
Run Code Online (Sandbox Code Playgroud)

这将返回一个像do一样的新数组uniq并O(n)及时工作.