Removing duplicate elements from an array in Swift

后端 未结 30 2755
遥遥无期
遥遥无期 2020-11-22 00:07

I might have an array that looks like the following:

[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]

Or, reall

30条回答
  •  天命终不由人
    2020-11-22 00:43

    One more Swift 3.0 solution to remove duplicates from an array. This solution improves on many other solutions already proposed by:

    • Preserving the order of the elements in the input array
    • Linear complexity O(n): single pass filter O(n) + set insertion O(1)

    Given the integer array:

    let numberArray = [10, 1, 2, 3, 2, 1, 15, 4, 5, 6, 7, 3, 2, 12, 2, 5, 5, 6, 10, 7, 8, 3, 3, 45, 5, 15, 6, 7, 8, 7]
    

    Functional code:

    func orderedSet(array: Array) -> Array {
        var unique = Set()
        return array.filter { element in
            return unique.insert(element).inserted
        }
    }
    
    orderedSet(array: numberArray)  // [10, 1, 2, 3, 15, 4, 5, 6, 7, 12, 8, 45]
    

    Array extension code:

    extension Array where Element:Hashable {
        var orderedSet: Array {
            var unique = Set()
            return filter { element in
                return unique.insert(element).inserted
            }
        }
    }
    
    numberArray.orderedSet // [10, 1, 2, 3, 15, 4, 5, 6, 7, 12, 8, 45]
    

    This code takes advantage of the result returned by the insert operation on Set, which executes on O(1), and returns a tuple indicating if the item was inserted or if it already existed in the set.

    If the item was in the set, filter will exclude it from the final result.

提交回复
热议问题