|
| 1 | +#include<iostream> |
| 2 | +#include<vector> |
| 3 | +#include<map> |
| 4 | +#include<set> |
| 5 | +#include<string> |
| 6 | +#include<list> |
| 7 | + |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +class Solution { |
| 11 | +public: |
| 12 | + double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { |
| 13 | + nums1.insert(nums1.end(), nums2.begin(), nums2.end()); |
| 14 | + sort(nums1.begin(), nums1.end()); |
| 15 | + for (vector<int>::iterator it = nums1.begin(); it!=nums1.end(); it++){ |
| 16 | + cout<<*it<<endl; |
| 17 | + } |
| 18 | + return nums1.size()%2? nums1[nums1.size()/2] : (nums1[nums1.size()/2]+nums1[nums1.size()/2-1])/2.0; |
| 19 | + } |
| 20 | + double findMedianSortedArrays2(vector<int>& nums1, vector<int>& nums2) { |
| 21 | + int cnt = nums1.size() + nums2.size(); |
| 22 | + cout<<"size:"<<cnt<<endl; |
| 23 | + if (cnt & 0x1) |
| 24 | + return findKth(&nums1[0], nums1.size(), &nums2[0], nums2.size(), cnt/2+1); |
| 25 | + else |
| 26 | + return (findKth(&nums1[0], nums1.size(), &nums2[0], nums2.size(), cnt/2) + findKth(&nums1[0], nums1.size(), &nums2[0], nums2.size(), cnt/2+1) )/2.0; |
| 27 | + } |
| 28 | + double findKth(int a[],int m, int b[], int n, int k){ |
| 29 | + cout<<m<<" "<<n<<endl; |
| 30 | + if (m>n){ |
| 31 | + return findKth(b,n, a, m, k); |
| 32 | + } |
| 33 | + if (m == 0){ |
| 34 | + return b[k-1]; |
| 35 | + } |
| 36 | + if (k == 1){ |
| 37 | + return min(a[0], b[0]); |
| 38 | + } |
| 39 | + int pa = min(k/2, m), pb = k-pa; |
| 40 | + if (a[pa-1] < b[pb-1]) |
| 41 | + return findKth(a+pa, m - pa , b, n, k-pa); |
| 42 | + else if (a[pa-1] > b[pb-1] ){ |
| 43 | + return findKth(a, m, b+pb, n-pb, k-pb); |
| 44 | + }else |
| 45 | + return a[pa-1]; |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +int main(){ |
| 50 | + Solution s; |
| 51 | + vector<int> a, b; |
| 52 | + a.push_back(1); |
| 53 | + a.push_back(3); |
| 54 | + b.push_back(2); |
| 55 | + b.push_back(4); |
| 56 | + for (auto v : a) |
| 57 | + cout<<v<<endl; |
| 58 | + for (vector<int>::iterator it = b.begin(); it!=b.end(); it++) |
| 59 | + cout<<*it<<endl; |
| 60 | + cout<<s.findMedianSortedArrays2(a, b)<<endl; |
| 61 | +} |
0 commit comments