【问题标题】:What is the time complexity of Array.enumerated() in swift?Array.enumerated() 的时间复杂度是多少?
【发布时间】:2018-11-24 15:23:11
【问题描述】:

我经常在我的代码中使用 enumerated(),例如:

for (index, element) in array.enumerated() {
    // ...
}

如果 enumerated() 花费 O(n) 时间,那么上述执行将花费 O(2n)。

我在这里感到困惑,因为 Apple 的文档没有提供任何时间复杂度的信息。

这会导致 O(2n) 还是 O(n)?

【问题讨论】:

  • 如果for 循环只通过数组一次,为什么它会花费 O(2n)?
  • swift不需要先计算enumerated()的结果吗?
  • O(2n) = O(n) 用于复杂性。如果您担心性能,请进行基准测试
  • 对,但是对于非常大的数组,O(n) 是否比 O(2n) 好?还是看起来一样?

标签: swift algorithm runtime


【解决方案1】:

Swift 现已开源,您可以从公共来源获取此信息。

来自GitHub

方法说明。

/// Returns a sequence of pairs (*n*, *x*), where *n* represents a
  /// consecutive integer starting at zero and *x* represents an element of
  /// the sequence.
  ///
  /// This example enumerates the characters of the string "Swift" and prints
  /// each character along with its place in the string.
  ///
  ///     for (n, c) in "Swift".enumerated() {
  ///         print("\(n): '\(c)'")
  ///     }
  ///     // Prints "0: 'S'"
  ///     // Prints "1: 'w'"
  ///     // Prints "2: 'i'"
  ///     // Prints "3: 'f'"
  ///     // Prints "4: 't'"
  ///
  /// When you enumerate a collection, the integer part of each pair is a counter
  /// for the enumeration, but is not necessarily the index of the paired value.
  /// These counters can be used as indices only in instances of zero-based,
  /// integer-indexed collections, such as `Array` and `ContiguousArray`. For
  /// other collections the counters may be out of range or of the wrong type
  /// to use as an index. To iterate over the elements of a collection with its
  /// indices, use the `zip(_:_:)` function.
  ///
  /// This example iterates over the indices and elements of a set, building a
  /// list consisting of indices of names with five or fewer letters.
  ///
  ///     let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
  ///     var shorterIndices: [SetIndex<String>] = []
  ///     for (i, name) in zip(names.indices, names) {
  ///         if name.count <= 5 {
  ///             shorterIndices.append(i)
  ///         }
  ///     }
  ///
  /// Now that the `shorterIndices` array holds the indices of the shorter
  /// names in the `names` set, you can use those indices to access elements in
  /// the set.
  ///
  ///     for i in shorterIndices {
  ///         print(names[i])
  ///     }
  ///     // Prints "Sofia"
  ///     // Prints "Mateo"
  ///
  /// - Returns: A sequence of pairs enumerating the sequence.

【讨论】:

  • 所以 enumerated() 的运行时间和 zip(indexes, elements) 一样吗? O(n) 是多少?
  • 实际实现在这里:github.com/apple/swift/blob/…
  • 谢谢亚历克斯!太棒了!