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:
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
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> combineArray;
for(int i = 0, j = 0;i< nums1.size() || j < nums2.size();)
{
if(i<nums1.size())
{
if(j<nums2.size())
{
if(nums1[i]<nums2[j])
{
combineArray.push_back(nums1[i++]);
}
else
{
combineArray.push_back(nums2[j++]);
}
}
else
{
combineArray.push_back(nums1[i++]);
}
}
else
{
combineArray.push_back(nums2[j++]);
}
}
//以上将二个有序数组组装到一个数组中,因二个数组都是有序数组,故复杂度可做到O(n)
int middle = (nums1.size() + nums2.size()) >> 1;//求取中位数
if(middle % 2 == 1)
{
return (double)combineArray[middle];
}
else
{
return ((double)combineArray[middle] + (double)combineArray[middle-1])/2.0;
}
//二分查找
}
};
解题思路:
- 将二个有序数组组装成一个有序数组,因二个数组都是有序,可采用比较数值大小,即可按大小组装成一个有序数组,千万不可遍历二个数组组装成一个数组,再排序,这样复杂度将不满足要求;
- 随后采用二分法即可获取最后结果。
总结:
1.习惯了IDE的自动补全,生写很是不适用;
2.不可调试,真是特别难受;
3.手撕代码真正考验对数据结构得理解;
4.继续加油,work,work。