如何合并数组中连续重复的元素? [英] How do you merge consecutive repeating elements in an array?

查看:40
本文介绍了如何合并数组中连续重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要合并数组中连续重复的元素,这样

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]

这会返回一个新数组,就像 uniqO(n) 时间内所做的和工作一样.

This returns a new array like uniq does and works in O(n) time.

这篇关于如何合并数组中连续重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆