4. Median of Two Sorted Arrays
Problem:
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
思路:
利用归并排序的原理将两个数组按序合并为一个数组,然后求中位数即可。
Solution (C++):
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
vector<int> res{};
int i = 0, j = 0;
while (i < m && j < n) {
if (nums1[i] < nums2[j]) {
res.push_back(nums1[i]);
++i;
}
else {
res.push_back(nums2[j]);
++j;
}
}
while (i < m) { res.push_back(nums1[i]); ++i; }
while (j < n) {res.push_back(nums2[j]); ++j; }
return (m+n-1)%2 ? double(res[(m+n)/2-1] + res[(m+n)/2]) / 2 : res[(m+n-1)/2];
}
性能:
Runtime: 24 ms Memory Usage: 8.3 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。