var numbers: [Int] = [1,1,2,3,4,4] // or [1,2,3,4,5,6,7,8]
let maxCount = numbers.filter({$0 == numbers.max()}).count
let minCount = numbers.filter({$0 == numbers.min()}).count
let secondHighest = numbers.filter(){
maxCount > 1 ? $0 == numbers.max() : $0 < numbers.max()
}.last
// prints 4 for [1,1,2,3,4,4] and 7 for [1,2,3,4,5,6,7,8]
let secondLowest = numbers.filter(){
minCount > 1 ? $0 == numbers.min() : $0 > numbers.min()
}.first
// prints 1 for [1,1,2,3,4,4] and 2 for [1,2,3,4,5,6,7,8]
4条答案
按热度按时间ercv8c1e1#
根据OP评论,如果冗余,第二个max、min将是阵列的最大值和最小值。我已经更新了方法。
p8ekf7hl2#
(1)找出最低值;(2)删除该值;(3)求出剩余的最小值:
secondLowest
是可选的,因为如果数组中的所有值都相同,则实际上没有“第二低”xmq68pz93#
//如何获取整数数组中的倒数第二个数字
41zrol4v4#
直接实现:(如苏尔汉所言?)