我有一个排序数组。我想遍历数组并在找到成对的值时递增一个计数器。我找不到解决这个问题的好办法。

var pairs = 0
    let colors = [10, 20, 20, 10, 10, 30, 50, 10, 20
    let sortedColors = colors.sorted{ $0 < $1}
    // [10, 10, 10, 10, 20, 20, 20, 30, 50] -> pairs should equal 3

    for i in 0..<colors.count - 1 {
        if sortedColors[i+1] != colors.count && sortedColors[i] == sortedColors[i+1] {
            pairs += 1
        }
    }

print(pairs)

最佳答案

另一种类似于@Sulthan's answer的方法是使用字典来计算出现次数,而不是NSCountedSet

let colors = [10, 20, 20, 10, 10, 30, 50, 10, 20]
let numberOfPairs = colors
  .reduce(into: [:]) { counts, num in counts[num, default: 0] += 1 }
  .reduce(0) { cumsum, kv in cumsum + kv.value / 2 } // 3

或者,在两个闭包中使用速记参数名:
let numberOfPairs = colors
  .reduce(into: [:]) { $0[$1, default: 0] += 1 }
  .reduce(0) { $0 + $1.value / 2 }

在上面的例子中,对于出现次数计数,我们使用问答中的@vacawama's answer,我最初将其用作重复标记此问答的目标。

07-24 09:50
查看更多