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
| #include<iostream> #include<vector> #include<string> using namespace std; double kth(vector<int>& nums1, int left1, int right1, vector<int>& nums2,int left2, int right2, int k){ if(right1-left1 > right2-left2){ return kth(nums2,left2,right2,nums1, left1,right1,k); } if(left1>right1) return nums2[left2+k-1]; if(k==1){ return min(nums1[left1], nums2[left2]); } int mid1=min(k/2, static_cast<int>(nums1.size()))-1, mid2=min(k/2,static_cast<int>(nums2.size()))-1; int res; if(nums1[left1+mid1]<nums2[left2+mid2]){ res=kth(nums1, left1+mid1+1,right1,nums2,left2,right2,k-(mid1+1)); }else { res=kth(nums1, left1,right1,nums2,left2+mid2+1,right2,k-(mid2+1)); } return res; }
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int len = nums1.size() + nums2.size(); if(len%2==0) return (kth(nums1, 0, nums1.size()-1,nums2,0,nums2.size()-1,len/2) + kth(nums1, 0, nums1.size()-1,nums2,0,nums2.size()-1,len/2+1))/(double)2; else return kth(nums1, 0, nums1.size()-1,nums2,0,nums2.size()-1,(len+1)/2); }
int main(){ vector<int> nums1={1}; vector<int> nums2={2,3,4,5,6}; cout<<findMedianSortedArrays(nums1, nums2)<<endl; return 0; }
|