LeetCode 两个排序数组的中位数4

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)).

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

有两个排序的数组nums1nums2分别为m和n。

找到两个排序数组的中位数。总运行时间复杂度应为O(log(m + n))。

思路

1.暴力法

(1)新建数组mum[]

(2)由于nums1和nums2是有序的数组,设置两个指针i,j分别指向nums1、nums2

(3)当nums1[i] < nums2[j]时就把nums1[i] 放到mum[k]里面

扫描二维码关注公众号,回复: 2317107 查看本文章

注意:

(1)如果其中一个数组位空,那么直接返回另一个数组的中位数即可

(2)要考虑边界条件,当其中一个数组(如果nums1)已经全部放入数组(mum)中时,另一个数组(nums2)再放入(mum)中时就无需和nums1进行比较

错误案例

猜你喜欢

转载自blog.csdn.net/qq_38362049/article/details/81155141
今日推荐