-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path004_Median_of_Two_Sorted_Arrays.cpp
94 lines (90 loc) · 2.02 KB
/
004_Median_of_Two_Sorted_Arrays.cpp
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "struct_define.h"
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
class Solution
{
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
bool jiou = (nums1.size()+nums2.size()) % 2 ? 1 : 0;//1ji 0ou
int pos = (nums1.size()+nums2.size())/2,posi = pos-1;
int index = -1, i = 0, j = 0, cur = 0, res = 0, resi = 0;
while (i < nums1.size() && j < nums2.size())
{
if(nums1[i] < nums2[j])
{
cur = nums1[i];
i++;
}
else// if(nums[1] )
{
cur = nums2[j];
j++;
}
index++;
if(index == posi)
{
resi = cur;
}
else if( index == pos)
{
res = cur;
if(jiou == 1)
return res;
else
return (res+resi)/2.0;
}
}
while (i < nums1.size())
{
cur = nums1[i];
i++;
index++;
if(index == posi)
{
resi = cur;
}
else if( index == pos)
{
res = cur;
if(jiou == 1)
return res;
else
return (res+resi)/2.0;
}
}
while (j < nums2.size())
{
cur = nums2[j];
j++;
index++;
if(index == posi)
{
resi = cur;
}
else if( index == pos)
{
res = cur;
if(jiou == 1)
return res;
else
return (res+resi)/2.0;
}
}
}
};
int main(int argc, char const *argv[])
{
Solution sol;
vector<int> a = {1,2,3},b={4,4,5};
cout<<sol.findMedianSortedArrays(a,b)<<endl;
return 0;
}