Remove duplicates from Array without using Hash Table

后端 未结 7 1675
终归单人心
终归单人心 2020-12-15 14:37

i have an array which might contain duplicate elements(more than two duplicates of an element). I wonder if it\'s possible to find and remove the duplicates in the array:

7条回答
  •  离开以前
    2020-12-15 15:23

    In functional languages you can combine sorting and unicification (is that a real word?) in one pass. Let's take the standard quick sort algorithm:

    - Take the first element of the input (x) and the remaining elements (xs)
    - Make two new lists
    - left: all elements in xs smaller than or equal to x
    - right: all elements in xs larger than x
    - apply quick sort on the left and right lists
    - return the concatenation of the left list, x, and the right list
    - P.S. quick sort on an empty list is an empty list (don't forget base case!)
    

    If you want only unique entries, replace

    left: all elements in xs smaller than or equal to x

    with

    left: all elements in xs smaller than x

    This is a one-pass O(n log n) algorithm.

    Example implementation in F#:

    let rec qsort = function
        | [] -> []
        | x::xs -> let left,right = List.partition (fun el -> el <= x) xs
                   qsort left @ [x] @ qsort right
    
    let rec qsortu = function
        | [] -> []
        | x::xs -> let left = List.filter (fun el -> el < x) xs
                   let right = List.filter (fun el -> el > x) xs
                   qsortu left @ [x] @ qsortu right
    

    And a test in interactive mode:

    > qsortu [42;42;42;42;42];;
    val it : int list = [42]
    > qsortu [5;4;4;3;3;3;2;2;2;2;1];;
    val it : int list = [1; 2; 3; 4; 5]
    > qsortu [3;1;4;1;5;9;2;6;5;3;5;8;9];;
    val it : int list = [1; 2; 3; 4; 5; 6; 8; 9]
    

提交回复
热议问题