快速最大连续正数
发布时间:2020-12-14 04:51:05 所属栏目:百科 来源:网络整理
导读:如何使用闭包计算最大连续正数? var numbers = [1,3,4,-1,-2,5,2,-3,-4,5]//in this case it should be 3print(numbers.reduce(0,{ $1 0 ? $0 + 1 : $0 } ))//this counts total positive numbers 解决方法 更新:更简单的解决方案:将数组拆分为多个切片
如何使用闭包计算最大连续正数?
var numbers = [1,3,4,-1,-2,5,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 解决方法
更新:更简单的解决方案:将数组拆分为多个切片
正元素,并确定最大切片长度: let numbers = [1,5] let maxConsecutive = numbers.split(whereSeparator: { $0 <= 0 }).map { $0.count }.max()! print(maxConsecutive) // 3 老答案:)使用Swift running sum的想法: let numbers = [1,5] let maxConsecutive = numbers.map({ () -> (Int) -> Int in var c = 0; return { c = $0 > 0 ? c + 1 : 0; return c } }()).max()! 这里map()将每个数组元素映射到连续正数的计数 [1,1,1] 转换创建为“立即评估 如果数组可能很大,则将其更改为 let maxConsecutive = numbers.lazy.map( ... ).max()! 这样就可以确定最大运行长度而无需创建中间数组. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |