假设我有一个数字数组:
let numbers: [Int] = [1,2,3,4,5,6,7,8]
我想选出该数组中第二低的数字,但我不想使用索引,我知道您可以使用 min/maxElement 点符号选择最低和最高的整数,那么我如何获得第二低的数字或第二高?
根据OP注释,第二个最大值,最小值将是数组的最大值和最小值,以防冗余。我已经更新了方法。
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]
(1)求最小值; (2) 删除该值; (3) 求剩余的最小值:
let numbers: [Int] = [1,2,3,4,5,6,7,8]
var lowest = numbers.minElement()!
var secondLowest = numbers.filter { $0 > lowest }.minElement()
secondLowest
是可选的,因为如果数组中的所有值都相同,则实际上不存在“第二低”
// 如何获取整数数组中第二小的数字
func secondLowest(arr: [Int]) -> Int {
let sortedArr = arr.sorted()
return sortedArr[1]
}
print(secondLowest(arr: [1,8,100,4,5,6,7,2,212])) // 2
func getSecondSmallest(arr:[Int])->Int{
var minNumber = arr.last ?? Int.max
var secondSmallest = arr.last ?? Int.max
for i in arr{
if minNumber > i {
minNumber = i
}else if i > minNumber && secondSmallest > i{
secondSmallest = i
}
}
return secondSmallest
}
直接实施:(正如Sulthan建议的那样?)
func secondMax(numbers: [Int]) -> Int {
let (_, second) = numbers.reduce((Int.min, Int.min)) {(max2: (first: Int, second: Int), value: Int) in
if value > max2.first {
return (value, max2.first)
} else if value > max2.second {
return (max2.first, value)
} else {
return max2
}
}
return second
}
print(secondMax([1,2,3,4,5,6,7,8])) //->7
print(secondMax([1,1,2,3,4,4])) //->4
print(secondMax([5,5,6,1,2,3,4])) //->5
print(secondMax([5,6,6,1,2,3,4])) //->6