快速连续最大正数 [英] swift maximum consecutive positive numbers
问题描述
如何使用闭包来计算最大连续正数?
How to count maximum consecutive positive numbers using closures?
var numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
//in this case it should be 3
print(numbers.reduce(0, { $1 > 0 ? $0 + 1 : $0 } ))//this counts total positive numbers
推荐答案
更新:更简单的解决方案:将数组拆分为
个正元素的切片,并确定最大切片长度:
Update: Simpler solution: Split the array into slices of positive elements, and determine the maximal slice length:
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let maxConsecutive = numbers.split(whereSeparator: { $0 <= 0 }).map { $0.count }.max()!
print(maxConsecutive) // 3
旧答案:)使用快速累计金额:
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let maxConsecutive = numbers.map({
() -> (Int) -> Int in var c = 0; return { c = $0 > 0 ? c + 1 : 0; return c }
}()).max()!
此处 map()
映射每个数组元素到元素位置为止的连续正
数的计数,在这种情况下
Here map()
maps each array element to the count of consecutive positive
numbers up to the elements position, in this case
[1, 2, 3, 0, 0, 1, 2, 0, 0, 0, 1]
已创建转换作为立即评估
关闭以捕获变量 c
,该变量保存当前
个连续的正数。转换将递增或重置 c
,
并返回更新后的值。
The transformation is created as an "immediately evaluated
closure" to capture a variable c
which holds the current number of
consecutive positive numbers. The transformation increments or resets c
,
and returns the updated value.
如果数组可能是大然后将其更改为
If the array is possibly large then change it to
let maxConsecutive = numbers.lazy.map( ... ).max()!
,以便确定最大运行长度而无需创建
中间数组。
so that the maximum run length is determined without creating an intermediate array.
这篇关于快速连续最大正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!