LeetCode 4. Median of Two Sorted Arrays(数组, 查找)
- By Scarb
- Scarb’s Blog
Tags:
- Binary Search
- Array
- Divide and Conquer
问题描述
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
解题思路
题意是给出两个排序好的数组,求中值。
第一个想到的方法是先将数组合并到一个数组中,然后取中值。但是时间复杂度为O(m+n)
,题目要求O(log (m+n))
。
可以将问题转化成求两个数组中求第k大的数,每次都删除一半比k小的数,类似二分查找。这样时间复杂度可以达到O(log(m+n))
两个数组为A和B,假设他们的元素个数都大于k/2
(如果小于k/2
, 那直接将这个数组末尾最大的数放入比较。)
将A[k/2-1]
与B[k/2-1]
进行比较,有以下三种情况
- A[k/2-1] < B[k/2-1] : A[0]到A[k/2-1]都小于第k个数,可以删除
- A[k/2-1] > B[k/2-1] : B[0]到B[k/2-1]都小于第k个数,可以删除
- A[k/2-1] == B[k/2-1] : 找到了第k大的数,直接返回A[k/2-1]
接着写一个递归函数,返回第k大的数,控制一些终止条件
- 当A或B是空的,直接返回B[k-1]或者A[k-1]
- 当k = 1,返回min(A[0], B[0])
- 当A[k/2-1] == B[k/2-1],返回A[k/2-1]或者B[k/2-1]
参考代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
const int s1 = nums1.size(), s2 = nums2.size();
int s = s1 + s2;
if (s % 2 == 1)
return find_kth(nums1.cbegin(), s1, nums2.cbegin(), s2, s / 2 + 1);
else
return (find_kth(nums1.cbegin(), s1, nums2.cbegin(), s2, s / 2) +
find_kth(nums1.cbegin(), s1, nums2.cbegin(), s2, s / 2 + 1)) / 2.0;
}
private:
int find_kth(vector<int>::const_iterator A, int m,
vector<int>::const_iterator B, int n, int k)
{
if (m > n) return find_kth(B, n, A, m, k);
if (m == 0) return *(B + k - 1);
if (k == 1) return min(*A, *B);
// divide k into two parts
int ia = min(k / 2, m), ib = k - ia;
if (*(A + ia - 1) < *(B + ib - 1))
return find_kth(A + ia, m - ia, B, n, k - ia);
else if (*(A + ia - 1) > *(B + ib - 1))
return find_kth(A, m, B + ib, n - ib, k - ib);
else
return A[ia - 1];
}
};
int main()
{
vector<int> nums1 = {1, 3, 5, 7, 9};
vector<int> nums2 = {2, 4, 6, 8, 10};
auto sl = Solution();
cout << sl.findMedianSortedArrays(nums1, nums2) << endl;
system("pause");
return 0;
}