两个有序数组合并成一个有序数组
2020-12-10 本文已影响0人
CocoaJason
extension ViewController {
func mergeOrderArray(With firstAry: Array<String>,
secondAry: Array<String>) -> Array<String> {
var FirstAry = firstAry
var SecondAry = secondAry
if FirstAry.isEmpty &&
SecondAry.isEmpty{
return []
}
if FirstAry.isEmpty {
return SecondAry
}
if secondAry.isEmpty {
return FirstAry
}
var endAry = [String]()
while true {
if Int(FirstAry.first!) ?? 0 < Int(SecondAry.first!) ?? 0 {
endAry.append(FirstAry.first!)
FirstAry.removeFirst()
} else {
endAry.append(SecondAry.first!)
SecondAry.removeFirst()
}
if FirstAry.isEmpty {
endAry.append(contentsOf: SecondAry)
break
}
if SecondAry.isEmpty {
endAry.append(contentsOf: FirstAry)
break
}
}
return endAry
}
}
print(mergeOrderArray(With: ["1","3","5","7","9"],
secondAry: ["1","2","17","20","35"]))
打印结果
["1", "1", "2", "3", "5", "7", "9", "17", "20", "35"]