-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-FindMedianSortedArrays.h
More file actions
67 lines (52 loc) · 1.34 KB
/
04-FindMedianSortedArrays.h
File metadata and controls
67 lines (52 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma once
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
/*
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
中位数核心:左右两边的个数相同
*/
class Solution
{
public:
double FindMedianSortedArrays(vector<int>& nums1, vector<int>& nums2);
};
double Solution::FindMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int nSize1 = nums1.size();
int nSize2 = nums2.size();
if (nSize1 > nSize2)
return FindMedianSortedArrays(nums2, nums1);
int nleft = 0;
int nRight = nSize1;
int nMedian = (nSize1 + nSize2 + 1) / 2;
int nMedian1 = 0;
int nMedian2 = 0;
while (nleft < nRight)
{
nMedian1 = nleft + (nRight - nleft) / 2;
nMedian2 = nMedian - nMedian1;
// LMax1 < Rmin2
if (nums1[nMedian1] < nums2[nMedian2 - 1])
{
nleft = nMedian1 + 1;
}
else
{
nRight = nMedian1;
}
}
nMedian1 = nleft;
nMedian2 = nMedian - nleft;
//L
int nCenter1 = max((nMedian1 <= 0 ? INT_MIN : nums1[nMedian1 - 1]),
(nMedian2 <= 0 ? INT_MIN : nums2[nMedian2 - 1]));
if ((nSize2 + nSize1) % 2 == 1)
return nCenter1;
int nCenter2 = min(nMedian1 >= nSize1 ? INT_MAX : nums1[nMedian1],
nMedian2 >= nSize2 ? INT_MAX : nums2[nMedian2]);
return (nCenter2 + nCenter1)*0.5;
}