Title Description
Given two ordered arrays of size and nums1 m and n nums2.
Please find both the median and orderly array, and requires time complexity of the algorithm is O (log (m + n)).
You can not assume nums1 and nums2 both empty.
Thinking
- Double pointer, a pointer nums1, nums2 a point, or if a small nums1 nums2 the pointer to the end, the nums1 pressed, or pressed into nums2. The time complexity of O (m + n)
- To achieve log (m + n), it is necessary dichotomy, such as parsing the
Code
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int len = len1 + len2;
vector<int> res;
if (len % 2 == 0) /*判断长度为偶数还是奇数*/
{
int i_nums1 = 0, i_nums2 = 0; /*双指针*/
while (i_nums1 + i_nums2 <= len / 2) /*判断是否到达中位数*/
{
if (i_nums2 == len2 || (i_nums1 < len1 && nums1[i_nums1] <= nums2[i_nums2]) )/*需要先判断i_nums2 是否到末尾,否则会报错,同时要取<=*/
{
res.push_back(nums1[i_nums1]);
i_nums1++;
}
else if (i_nums1 == len1 || (i_nums2 < len2 && nums2[i_nums2] < nums1[i_nums1]) )
{
res.push_back(nums2[i_nums2]);
i_nums2++;
}
}
return (res[res.size() - 1] + res[res.size() - 2]) / 2.0;
}
else
{
int i_nums1 = 0, i_nums2 = 0;
while (i_nums1 + i_nums2 <= (len - 1) / 2)
{
if (i_nums2 == len2 || (i_nums1 < len1 && nums1[i_nums1] <= nums2[i_nums2]))
{
res.push_back(nums1[i_nums1]);
i_nums1++;
}
else if (i_nums1 == len1 || (i_nums2 < len2 && nums2[i_nums2] < nums1[i_nums1]))
{
res.push_back(nums2[i_nums2]);
i_nums2++;
}
}
return res[res.size() - 1] * 1.0;
}
return 0.0;
}
};