代码之家  ›  专栏  ›  技术社区  ›  l30c0d35

从集合初始化数组是否很复杂?如果是,它是什么?

  •  0
  • l30c0d35  · 技术社区  · 5 年前

    Swift:选项1

    var dictionaryWithoutDuplicates = [Int: Int]()
    for item in arrayWithDuplicates {
       if dictionaryWithoutDuplicates[item] == nil {
          dictionaryWithoutDuplicates[item] = 1
       }
    }
    print(dictionaryWithoutDuplicates.keys)
    // [1,2,3,4]
    

    选项2

    let arrayWithDuplicates = [1,2,3,3,2,4,1]
    let arrayWithoutDuplicates = Array(Set(arrayWithDuplicates))
    print(arrayWithoutDuplicates)
    // [1,2,3,4]
    

    对于第一个选项,可能有一种更优雅的方法来完成它,但这不是我的观点,我只是想展示一个复杂度为n的例子。 两个选项都返回一个没有重复项的数组。因为第一个选项的复杂性是O(n),我想知道第二个选项是否具有复杂性,如果是,它是什么?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Alexander    5 年前

    Set Set<T> [T: Void] Dictionary<T, Void>

    O(arrayWithDuplicates.count)