MedianOfTwoSortedArrays

题目

Median of Two Sorted Arrays
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.

Example 1:

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

The median is 2.0

Example 2:

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

The median is (2 + 3)/2 = 2.5

解题报告

理解题意

  • 两个数组:m & n (已排好序)
  • 找到两个数组的中间节点
  • 时间复杂度要求:\(\mathcal{O(log(m+n))}\)

理解例子

例子 1

  • nums1:[1, 3]
  • nums2:[2]
  • 中间的元素为 2, 因为总共3个元素:1,2,3;

例子 2

  • nums1:[1, 2]
  • nums2:[3,4]
  • 中间的元素为 2.5, 因为总共4个元素:[1,2,3,4];(2+3)/2 = 2.5

思路

  • 从例子来看,把两个数组的元素分别插入到一个新的数组,然后再遍历找到居中的元素,时间复杂度为\(\mathcal{O(m+n)}\)。
  • 要求时间复杂度为 \(\mathcal{O(log(m+n))}\),这个算是比较强烈的提示(对n个元素折半查找-BinarySearch就是 \(\mathcal{O(log(n))}\))
  • 那么剩下的问题就是如何折半,哪里到哪里折半,怎么调整lr.
  • 其实最终的找到的点:左半部分小于右半部分。第一个数组的左半部分小于第二个数组的右半部分,第二个数组的左半部分小于第二个数组的右半部分。并且是合并后数组中间的部分。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 非递归版本
int binarySearch(vector<int> &vec, int result){
int l = 0, r = vec.size();
while (l < r) {
int mid = (r + l)/2;
if (vec[mid] == result) return mid; // found the result
if (vec[mid] > result) { // the index is on the left side of mid
r = mid;
} else {
l = mid+1;
}
}
return l;
}

// 递归版本
int binarySearch(vector<int> &vec, int l, int r, int result){
int mid = (l + r) / 2;
if (vec[mid] == result) return mid;
if (vec[mid] > result) {
return binarySearch(vec, l, mid, result);
} else {
return binarySearch(vec, mid+1, r, result);
}
}
  • 假定合并后的数组为C
  • 从第一个数组取m1个元素,第二个元素取m2个元素,来构成前k个元素,来满足第k/k+1个元素就是中位数的候选数。其中k = m1 + m2 = (m + n + 1)/2。加 1 是为了不用考虑奇偶。
  • 找到的元素为 \(\mathcal{Avg(max(A[m-1], B[n-1]), min(A[m],B[n]))}\),根据总数奇数和偶数。

流程

  • 如果某一个为空,则返回另一个数组的中间元素即可
  • 遍历完成后返回最大的长度
  • 时间复杂度:线性时间 \(\mathcal{O(n)}\)

代码

1
2
3
4
5
6
7
8
9
class Solution {
public:
int findMediaSortedArrays(vector<int> &nums1, vector<int> &nums2) {
const int m = nums1.size();
const int n = nums2.size();
if (m > n) return findMediaSortedArrays(nums2, nums1);

}
};

时间复杂度

如一开始分析:时间复杂度:线性时间 \(\mathcal{O(n)}\)

空间复杂度

额外申请了和一个链表,因此空间复杂度也为 \(\mathcal{O(max(len(l1), len(l2)))}\)

作者

shouyi.www

发布于

2019-11-23

更新于

2025-01-30

许可协议

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×