【发布时间】:2021-10-17 23:28:28
【问题描述】:
我正在使用一个排序函数,该函数接受一个已经按降序排序的 Int 数组,并将一个新的 Int 放置在正确的位置。 (即,如果我的排序数组是 [10, 7, 2] 并且新的 int 是 5,则该函数将返回 [10, 7, 5, 2])。执行此操作的函数一旦找到新 Int 的正确位置,就会将原始数组切片为新 Int 位置之前和之后的项目,然后将切片与新 Int 组合。
我遇到的问题是这不会给我一个数组,而是一个数组切片。
代码:
func addToSorted(sorted: [Int], new: Int) -> [Int] {
if sorted.count == 0 {
return [new]
} else {
for index in 0..<sorted.count {
let item = sorted[index]
if new > item {
return sorted[..<index] + [new] + sorted[index...]
}
}
}
}
let result = addToSorted(sorted: [10, 7, 2], new: 5)
print(result) // expected [10, 7, 5, 2]
【问题讨论】:
标签: arrays swift sorting slice