【问题标题】:Count the occurences a particular integer has in an array [duplicate]计算特定整数在数组中的出现次数[重复]
【发布时间】:2016-03-19 10:38:56
【问题描述】:

如何计算特定数字在数组中出现的次数。 我找不到快速的方法。有人可以指导我吗?

谢谢:)

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    Xcode 9 或更高版本 • Swift 4 或更高版本

    在 Swift 4 中,您可以使用新的 Dictionary 方法reduce(into:),如下所示:

    extension Sequence where Element: Hashable {
        var frequency: [Element: Int] {
            return reduce(into: [:]) { $0[$1, default: 0] += 1 }
        }
        func frequency(of element: Element) -> Int {
            return frequency[element] ?? 0
        }
    }
    

    游乐场测试:

    let numbers = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
    print(numbers.frequency) // [2: 1, 4: 1, 5: 2, 3: 1, 1: 3, 0: 2]
    
    print(numbers.frequency(of: 0))   // 2  
    print(numbers.frequency(of: 1))   // 3
    print(numbers.frequency(of: 2))   // 1
    print(numbers.frequency(of: 3))   // 1
    print(numbers.frequency(of: 4))   // 1
    print(numbers.frequency(of: 5))   // 2
    

    通过扩展 Collection,它也支持字符串

    "aab".frequency   // ["a": 2, "b": 1]
    

    【讨论】:

      【解决方案2】:

      创建一个字典,存储第一次找到的数字,并用 1 初始化键。否则递增。

      let numArray = [1, 2, 2, 2, 5]
      var numCount:[Int:Int] = [:]
      
      for item in numArray {
          numCount[item] = (numCount[item] ?? 0) + 1
      
      for (key, value) in numCount {
          println("\(key) occurs \(value) time(s)")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        • 1970-01-01
        • 1970-01-01
        • 2021-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多