How can I detect if a list contains duplicates?

橙三吉。 提交于 2019-12-10 19:16:21

问题


I want to know if a list contains any value more than once. Here's what I have.

has_dupes(List) ->
    has_dupes(List, []).

has_dupes([Item|List], Seen) ->
    case lists:filter(fun(Elem) -> Elem == Item end, Seen) of
        [] ->
            has_dupes(List, [Item|Seen]);
        _ ->
            true
    end;
has_dupes([], _Seen) ->
    false.

Is there a simpler/more concise/more idiomatic way to do this? I'm pretty new at the Erlang.


回答1:


erlang:length(List) == sets:size(sets:from_list(List)).



回答2:


What about this possible solution?

has_dupes([H|T]) -> 
 case lists:member(H, T) of 
  true -> true;
  false -> has_dupes(T)
 end;
has_dupes([]) -> false. 



回答3:


Had a 2 million element list of binaries to check. Ran these two versions for speed. usort appears to win, 6 seconds vs 316 seconds.

14> timer:tc(fun() ->  erlang:length(X) == erlang:length(lists:usort(X))  end).
{6825493,false}
15> timer:tc(fun() ->  erlang:length(X) == sets:size(sets:from_list(X)) end).  
{316297882,false}


来源:https://stackoverflow.com/questions/4000986/how-can-i-detect-if-a-list-contains-duplicates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!