iOS -选择整数数组中第二小的数字

gab6jxml  于 2023-01-22  发布在  iOS
关注(0)|答案(4)|浏览(138)

假设我有一个数字数组:

let numbers: [Int] = [1,2,3,4,5,6,7,8]

我想找出数组中倒数第二小的数,但我不想用下标,我知道你可以用min/maxElement点标记法,找出最小和最大的整数,那么我怎么才能得到倒数第二小或倒数第二大的数呢?

ercv8c1e

ercv8c1e1#

根据OP评论,如果冗余,第二个max、min将是阵列的最大值和最小值。我已经更新了方法。

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]
p8ekf7hl

p8ekf7hl2#

(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是可选的,因为如果数组中的所有值都相同,则实际上没有“第二低”

xmq68pz9

xmq68pz93#

//如何获取整数数组中的倒数第二个数字

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
41zrol4v

41zrol4v4#

直接实现:(如苏尔汉所言?)

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

相关问题