There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
有两个大小分别为m和n的编号为s1和编号为s2的排序数组。
求两个排序数组的中值。总的运行时复杂度应该是O(log (m+n))。
您可以假设nums1和nums2不能都是空的。
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
Idea:
Since nums1 and nums2 are both sorted, so I only compare the nums1[index1] to nums2[index2] and inserted the minimum value into a temporary container array (insert the value into first position if it is lesser than first value, otherwise insert it to the last). The index would be increased if the number at that position was inserted into the container. Finally, insert the rest of numbers inside the nums1 or numser 2 to the container if they still have numbers left.
因为nums1和nums2都是排序的,所以我只比较nums1[index1]和nums2[index2],并将最小值追加到一个临时容器数组中 (如果值小于第一个值,则将其插入到第一个位置,否则将其插入到最后一个位置)。如果将该位置的数字插入到容器中,则索引将增加。最后,如果nums1或numser 2中还有剩余的数字,将剩下的数字插入到容器中。
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
var container = [Int]()
let m = nums1.count
let n = nums2.count
var index1 = 0
var index2 = 0
while index1 < m && index2 < n{
let nums1LessthanNums2 = nums1[index1] <= nums2[index2]
let minimum = nums1LessthanNums2 ? nums1[index1] : nums2[index2]
if container.count == 0{
container.append(minimum)
}
else{
if minimum <= container[0]{
container.insert(minimum, at: 0)
}
else{
container.insert(minimum, at: container.count)
}
}
if nums1LessthanNums2{
index1 += 1
}
else{
index2 += 1
}
}
if index1 == m{
container.append(contentsOf: nums2.dropFirst(index2))
}
else if index2 == n{
container.append(contentsOf: nums1.dropFirst(index1))
}
let containerSize = m + n
let median = container.count % 2 == 0 ? (Double(container[containerSize / 2]) + Double(container[containerSize / 2 - 1])) / 2.0: Double(container[(containerSize / 2)])
return median
}