Array remove duplicate elements

前端 未结 12 1504
陌清茗
陌清茗 2020-11-27 16:17

I have an unsorted array, what is the best method to remove all the duplicates of an element if present?

e.g:

a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]
         


        
12条回答
  •  时光取名叫无心
    2020-11-27 16:47

    This can be done in amortized O(n) using a hashtable-based set.

    Psuedo-code:

    s := new HashSet
    c := 0
    for each el in a
      Add el to s.
        If el was not already in s, move (copy) el c positions left.
        If it was in s, increment c. 
    

提交回复
热议问题