leetcode4
2021-07-27 本文已影响0人
大写的空气
给定两个大小分别为 m 和 n 的正序(从小到大)数组 num1 和 num2。请你找出并返回这两个正序数组的 中位数
当数组为偶数个时,中位数为两位数字的平均值
func findMedianSortedArrays(_ num1: [Int], _ num2: [Int]) -> Double{
guard num1.count > 0 || num2.count > 0 else {
return -1.0
}
var middle = 0.0 //中位数, 当数组为偶数个时,中位数为两位数字的平均值
if num1.count == 0 { //num1为空数组
let mid = num2.count / 2
if num2.count%2 == 0 { //偶数个,取数组最后两个的平均值
middle = Double(num2[mid] + num2[mid-1])/2.0
}else{
middle = Double(num2[mid])
}
return middle
}else if num2.count == 0 { //num2为空数组
let mid = num1.count / 2
if num1.count%2 == 0 { //偶数个,取数组最后两个的平均值
middle = Double(num1[mid] + num1[mid-1])/2.0
}else{
middle = Double(num1[mid])
}
return middle
}
var merg = [Int]()
var left=0, right=0
while left < num1.count, right < num2.count {
if merg.count > (num2.count+num1.count)/2 { //因为是取中位数,因此舍弃后续需排序的元素,直接结束
break
}
if num1[left] < num2[right] { //num1的第一个元素小于num2的第一个元素
merg.append(num1[left])
left += 1
}else{
merg.append(num2[right])
right += 1
}
}
let miss = (num2.count+num1.count)/2+1 - merg.count //数组达到标准还差多少个
if miss > 0 {//两个数组长度偏差过大,新数组还不超总长度的一半
if num1.count > num2.count { //num1数组更长
let has = merg.count-num2.count //num1数组中已经加入到merg数组中元素的个数
merg += num1[has..<(has+miss)]
}else if num2.count == num1.count { //两个数组一样长,此时可能在num1取值,也可能在num2取值. 总的原则是在大数的数组中取值
if num1.last! > num2.last! {
let has = merg.count-num2.count //num1数组中已经加入到merg数组中元素的个数
merg += num1[has..<(has+miss)]
}else{
let has = merg.count-num1.count //num1数组中已经加入到merg数组中元素的个数
merg += num2[has..<(has+miss)]
}
}
else{
let has = merg.count-num1.count //num1数组中已经加入到merg数组中元素的个数
merg += num2[has..<(has+miss)]
}
}
if (num2.count+num1.count)%2 == 0 { //偶数个,取数组最后两个的平均值
middle = Double(merg[merg.count-1] + merg[merg.count-2])/2.0
}else{
middle = Double(merg.last!)
}
return middle
}
print(findMedianSortedArrays([100001], [100000]))