elixir-lang在列表中查找非重复元素 [英] elixir-lang Finding non-duplicate elements in a list

查看:71
本文介绍了elixir-lang在列表中查找非重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从列表中查找非重复值,例如

I'm trying to find non duplicate values from a list e.g.

原始列表:

iex> list = [2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 10]
[2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 10]

iex> unique = Enum.uniq(list)
[2, 3, 4, 5, 6, 7, 8, 9, 10]

iex> nondupes = unique -- Enum.uniq(list -- unique)
[2, 3, 5, 7]

结果:[2、3、5、7]

result: [2, 3, 5, 7]

我想知道在elixir/erlang中是否有更好的方法实现这一目标

I was wondering if there was a better way to achieve this in elixir/erlang

推荐答案

对于大型数据可能更快的另一种方法(不一定更好)是从元素到它们的计数建立映射,然后选择count为1的那些:

Another method (not necessarily better) that might be faster for large data is to build a map from elements to their counts and select the ones where count is 1:

list
|> Enum.reduce(%{}, fn (el, acc) -> Dict.put(acc, el, Dict.get(acc, el, 0) + 1) end)
|> Enum.filter(fn {key, val} -> val == 1 end)
|> Enum.map(fn {key, val} -> key end)

这应具有运行时 O(n * log(n)),而不是您的解决方案要求的 O(n ^ 2)(如果整个输入已经是唯一的).

This should have runtime O(n * log(n)) instead of the O(n ^ 2) your solution requires (the subtraction should be quadratic if the whole input is unique already).

这篇关于elixir-lang在列表中查找非重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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