我有以下数组
var numbers = [2, 4, 4, 2, 3, 1]
序列很重要,我需要找到最低值的索引。 那么我怎样才能找到最低价值的指数呢?我需要能够调用 numbers[lowestValueIndex] 并获得正确的值
感谢任何帮助
答案 0 :(得分:2)
我一直认为在这种类型的场景中扩展数组提供了一个更清晰的调用站点。
extension Array where Element == Int {
func lowest() -> (value: Element, positions:[Index])? {
guard !isEmpty else {return nil } //you may wish to throw an error rather than return nil
return indices.reduce( (value: Element.max, positions: [Index]() ) ) {
switch self[$1] {
case let x where x < $0.value: return (value: self[$1], positions:[$1])
case let x where x > $0.value: return $0
default: return ($0.value, $0.positions + [$1])
}
}
}
}
可以使用 _ 或模式匹配来简化 switch 语句,但我觉得这种更详细的方法更容易理解。与可选返回类型相比,抛出错误或返回 Result 可能是处理空数组更好的方式,但会增加答案的膨胀,如果愿意,可以稍后由 OP 添加。
[2,3,6,1,7,3,1,6,7].lowest() // (value: 1, positions: [3, 6])
[2,3,6,6,7,3,1,6,7].lowest() // (value: 1, positions: [6])
[Int]().lowest() // nil
答案 1 :(得分:1)
可以使用min(by:)
数组方法;诀窍是对数组的 indices
属性进行操作,以便您可以返回相关索引:
func minIndex(someArray: [Int]) -> Int? {
return someArray.indices.min { someArray[$0] < someArray[$1] }
}
如果数组为空,函数将返回nil
。
为简单起见,我将其显示为函数。当然,如果您愿意,您可以将其作为 Array
上的扩展来实现。
答案 2 :(得分:1)
如果您只需要一个值,其他答案将处理该怎么做。否则……
let numbers = [2, 4, 4, 2, 3, 1, 1]
// [(offset 5, element 1), (offset 6, element 1)]
numbers.min().map { min in
numbers.enumerated().filter { $0.element == min }
}
如果您需要对数组进行排序以供进一步使用,前缀比过滤器更好。
let sorted =
[2, 4, 4, 2, 3, 1, 1]
.enumerated()
.sorted(by: \.element)
sorted.first.map { first in
sorted.prefix { $0.element == first.element }
}
public extension Sequence {
/// Sorted by a common `Comparable` value.
func sorted<Comparable: Swift.Comparable>(
by comparable: (Element) throws -> Comparable
) rethrows -> [Element] {
try sorted(by: comparable, <)
}
/// Sorted by a common `Comparable` value, and sorting closure.
func sorted<Comparable: Swift.Comparable>(
by comparable: (Element) throws -> Comparable,
_ areInIncreasingOrder: (Comparable, Comparable) throws -> Bool
) rethrows -> [Element] {
try sorted {
try areInIncreasingOrder(comparable($0), comparable($1))
}
}
}
答案 3 :(得分:0)
首先需要定义输入数组中重复值的行为。 完成后,试试这个:
func returnLowestValueIndex(array: [Int]) -> Int? {
guard !array.isEmpty else { return nil }
var lowestValueIndex: Int = 0
for (index, value) in array.enumerated() {
if value < array[lowestValueIndex] {
lowestValueIndex = index
}
return lowestValueIndex
}
var numbers = [2, 4, 4, 2, 3, 10]
returnLowestValueIndex(array: numbers)