加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:50:30 所属栏目:百科 来源:网络整理
导读:我需要合并一个数组中的连续重复元素 [1,2,3,1] 变 [1,1] #uniq不能用于此目的.为什么?因为#uniq会产生这个: [1,3] 解决方法 def remove_consecutive_duplicates(xs) [xs.first] + xs.each_cons(2).select do |x,y| x != y end.map(:last)endremove_consec
我需要合并一个数组中的连续重复元素
[1,2,3,1]

[1,1]

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

[1,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,1])
#=> [1,1]

这将返回一个像uniq一样的新数组,并在O(n)时间内工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读