-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode004.cpp
71 lines (69 loc) · 1.54 KB
/
leetcode004.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
/*************************************************************************
> File Name: leetcode004.cpp
> Author:
> Mail:
> Created Time: Tue 20 Sep 2016 07:25:20 PM PDT
************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
int findkth(vector<int>& nums1,vector<int> nums2,int k)
{
int j = 0;
int m = 0;
for(int i = 0 ;i < k - 1 ; i++)
{
if(j >= nums1.size() && m < nums2.size())
{
m++;
}
else if(j < nums1.size() && m >= nums2.size())
{
j++;
}
else if(nums1[j] > nums2[m])
{
m++;
}
else
{
j++;
}
}
if(j >= nums1.size())
{
return nums2[m];
}
else if(m >= nums2.size())
{
return nums1[j];
}
else
{
return nums1[j] > nums2[m] ? nums2[m]:nums1[j];
}
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len = nums1.size() + nums2.size();
if(len % 2 == 0)
{
return (findkth(nums1,nums2,len/2) + findkth(nums1,nums2,len/2+1))/2.0;
}
else
{
return findkth(nums1,nums2,len/2+1);
}
}
int main()
{
vector<int> data1;
data1.push_back(1);
data1.push_back(2);
vector<int> data2;
data2.push_back(3);
vector<int> data3;
data3.push_back(3);
data3.push_back(4);
cout << findMedianSortedArrays(data1,data2) << endl;
cout << findMedianSortedArrays(data1,data3) << endl;
}