📌  相关文章
📜  数组 swift 代码示例中最常见的元素

📅  最后修改于: 2022-03-11 15:01:02.849000             🧑  作者: Mango

代码示例1
func mostFrequent(array: [Int]) -> (value: Int, count: Int)? {
    var counts = [Int: Int]()

    array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }

    if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
        return (value, count)
    }

    // array was empty
    return nil
}

if let result = mostFrequent(array: [1, 3, 2, 1, 1, 4, 5]) {
    print("\(result.value) occurs \(result.count) times")    
}