题目:
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:
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( log (m+n) )
分析:
按照常规方法,能在线性时间内(O (m+n) )解决问题:使用归并排序后再求中位数(本题的后台数据比较弱,可以水过去),但是题目有复杂度要求...
看到题目要求的时间复杂度,就能想到用二分(之前遇到过一道类似的题目,用的二分解决的问题),但是构思了很久,还是控制不好算法的具体细节,无从下手....
虽然也搜索题解看了一下,但是确实没能完全理解,后边再说吧,先留个坑...
代码一:(时间复杂度 O(m+n))
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
auto result = merge(nums1, nums2);
auto mid = (result.size() - 1) >> 1;
if (result.size() & 1) {
return result[mid];
} else {
return (result[mid] + result[mid + 1]) / 2.0;
}
}
vector<int> merge(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
int index1 = 0, index2 = 0;
while (index1 < nums1.size() && index2 < nums2.size()) {
if (nums1[index1] < nums2[index2]) {
result.push_back(nums1[index1]);
++ index1;
} else {
result.push_back(nums2[index2]);
++ index2;
}
}
while (index1 < nums1.size()) {
result.push_back(nums1[index1]);
++ index1;
}
while (index2 < nums2.size()) {
result.push_back(nums2[index2]);
++ index2;
}
return result;
}
};
代码二:(时间复杂度 O( log (m+n) ))
//待后续补充
本文探讨了两个有序数组中位数的求解方法。提出了两种算法实现:一种为归并排序后的直接查找(时间复杂度O(m+n)),另一种则是在O(log(m+n))时间复杂度内完成的更高效解决方案。
637

被折叠的 条评论
为什么被折叠?



