How to find duplicates in a list?

后端 未结 5 1658
梦毁少年i
梦毁少年i 2020-12-09 15:25

I have a list of unsorted integers and I want to find those elements which have duplicates.

val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102         


        
5条回答
  •  余生分开走
    2020-12-09 15:31

    Another approach is to use foldLeft and do it the hard way.

    We start with two empty sets. One is for elements that we have seen at least once. The other for elements that we have seen at least twice (aka duplicates).

    We traverse the list. When the current element has already been seen (seen(cur)) it is a duplicate and therefore added to duplicates. Otherwise we add it to seen. The result is now the second set that contains the duplicates.

    We can also write this as a generic method.

    def dups[T](list: List[T]) = list.foldLeft((Set.empty[T], Set.empty[T])){ case ((seen, duplicates), cur) => 
      if(seen(cur)) (seen, duplicates + cur) else (seen + cur, duplicates)      
    }._2
    
    val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102)
    
    dups(dup) //Set(1,5,101)
    

提交回复
热议问题