Median of Two Sorted Arrays[hard]
Description
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
Analysis
这道题目就是求两个有序数组的中位数,一种最笨的方法就是将这两个数组合二为一,之后直接得到中位数,但想要合二为一,我们不得不遍历两个数组,注意到题目的要求是算法的复杂度为O(log (m+n))。
我们可以首先直接根据两个数组的长度得到中位数的位置,即target,然后在分别遍历数组的过程中找到中位数。
当数组的总长度为偶数时,中位数为中间两数的平均数;为奇数时,中位数就是中间的数,即target。
在数组中使用h1和h2,必须保证h1 < l1, h2 < l2
- 当h1 == l1 && count 未达到target, 只需在nums2中计算中位数
- 当h2 == l2 && count 未达到target, 只需在nums1中计算中位数
但此时的计算要注意数组的下标从0开始。
剩下的就是我们不断地更新count,h1, h2的值,每进行一次循环更新一次count的值,之后比较nums[h1]与nums[h2]的大小,同时判断count是否等于target,当count==target :
- 数组总长度为奇数,直接返回比较较小的值;
- 数组总长度为偶数,需要进一步判断数组的下一个数是否越界;
本题还需注意的就是最后返回数据的类型为double。
Solution
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int l1 = nums1.size();
int l2 = nums2.size();
int sum = l1+l2;
int target = sum/2;
bool flag = false;
if (sum%2 == 0) {
flag = true;
} else {
target = target+1;
}
int h1 = 0;
int h2 = 0;
int count = 0;
while (h1 < l1&& h2 < l2) {
count++;
if (nums1[h1] <= nums2[h2]) {
if (count == target&&flag) {
if ((h1 + 1) == l1) {
return (double)(nums1[h1]+nums2[h2])/2;
} else {
if (nums1[h1+1] <= nums2[h2]) {
return (double)(nums1[h1]+nums1[h1+1])/2;
} else {
return (double)(nums1[h1]+nums2[h2])/2;
}
}
}
else if (count == target&&!flag) {
return (double)nums1[h1];
}
h1++;
} else {
if (count == target&&flag) {
if ((h2 + 1) == l2) {
return (double)(nums1[h1]+nums2[h2])/2;
} else {
if (nums2[h2+1] <= nums1[h1]) {
return (double)(nums2[h2]+nums2[h2+1])/2;
} else {
return (double)(nums2[h2]+nums1[h1])/2;
}
}
}
else if (count == target&&!flag) {
return (double)nums2[h2];
}
h2++;
}
}
if (h1 == l1) {
if (flag) {
return (double)(nums2[target-l1-1]+ nums2[target-l1])/2;
} else {
return (double)nums2[target-l1-1];
}
}
else if (h2 == l2) {
if (flag) {
return (double)(nums1[target-l2-1]+ nums1[target-l2])/2;
} else {
return (double)nums1[target-l2-1];
}
}
}
};
Discussion
在解题过程中,由于很多情况的忽略,浪费了很多时间。
完成以后,通过学习此题的答案,发现了利用了分治的思想,运用了递归,使得解题的过程更加简单。
427

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



