天天看點

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           

有兩個排序的數組nums1和nums2分别為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]裡面

注意:

(1)如果其中一個數組位空,那麼直接傳回另一個數組的中位數即可

(2)要考慮邊界條件,當其中一個數組(如果nums1)已經全部放入數組(mum)中時,另一個數組(nums2)再放入(mum)中時就無需和nums1進行比較

錯誤案例

繼續閱讀