Median of Two Sorted Arrays

hard 原题链接:https://leetcode.com/problems/median-of-two-sorted-arrays/

Median of Two Sorted Arrays

原题链接:https://leetcode.com/problems/median-of-two-sorted-arrays/

描述

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

例子

Input: nums1 = [1,3], nums2 = [2]

Output: 2.00000

Explanation: merged array = [1,2,3] and median is 2.

Input: nums1 = [1,2], nums2 = [3,4]

Output: 2.50000

Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Input: nums1 = [0,0], nums2 = [0,0]

Output: 0.00000

Input: nums1 = [], nums2 = [1]

Output: 1.00000

Follow up:

The overall run time complexity should be O(log (m+n)).

Constrain:

  • nums1.length == m

  • nums2.length == n

  • 0 <= m <= 1000

  • 0 <= n <= 1000

  • 1 <= m + n <= 2000

  • -106 <= nums1[i], nums2[i] <= 106

解法一

O(m+n)的解法比较直观,直接merge两个数组,然后找到第k大的元素(题中及寻找中位数) 但是merge之后,如果使用“排序”的操作,时间花费是expensive的。

也可以用一个计数器,记录当前已经找到第m大的元素,同时再使用两个指针pA和pB,分别指向A和B数组的第一个元素,使用merge sort的原理:

如果数组A当前元素小,则pA++,同时m++;

如果数组B当前元素小,则pB++,同时m++。

最终当m等于k的时候,及得到答案,时间复杂度:O(K),空间复杂度O(1) 如果当K很接近m+n的时候,这个方法还是O(m+n)的。

解法二

递归的方法:

总结

最后更新于

这有帮助吗?