\
此题与之前在一个数组中找中位数类似,可以在基础上修改。
不过在入堆的时候需要对两个数组大小元素进行判断,小的入堆。
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { priority_queue<int, vector<int>, greater<int> > minheap; priority_queue<int, vector<int>, less<int> > maxheap; int i = 0; int j = 0; while(i<nums1.size()&&j<nums2.size()){ if(minheap.size()==maxheap.size()){ if(nums1[i]<=nums2[j]){ cout<<"nums1_"<<i<<"_:"<<nums1[i]<<endl; maxheap.push(nums1[i]); int tmp = maxheap.top(); maxheap.pop(); minheap.push(tmp); i++; }else{ cout<<"nums2_"<<j<<"_:"<<nums2[j]<<endl; maxheap.push(nums2[j]); int tmp = maxheap.top(); maxheap.pop(); minheap.push(tmp); j++; } }else { if(nums1[i]<=nums2[j]){ cout<<"nums11_"<<i<<"_:"<<nums1[i]<<endl; minheap.push(nums1[i]); int tmp = minheap.top(); minheap.pop(); maxheap.push(tmp); i++; }else{ cout<<"nums22_"<<j<<"_:"<<nums2[j]<<endl; minheap.push(nums2[j]); int tmp = minheap.top(); minheap.pop(); maxheap.push(tmp); j++; } } } while(i<nums1.size()&&j>=nums2.size()){ if(minheap.size()==maxheap.size()){ maxheap.push(nums1[i]); int tmp = maxheap.top(); maxheap.pop(); minheap.push(tmp); cout<<"nums1_"<<i<<"_:"<<nums1[i]<<endl; i++; }else{ minheap.push(nums1[i]); int tmp = minheap.top(); minheap.pop(); maxheap.push(tmp); cout<<"nums1_"<<i<<"_:"<<nums1[i]<<endl; i++; } } while(j<nums2.size()&&i>=nums1.size()){ if(minheap.size()==maxheap.size()){ maxheap.push(nums2[j]); int tmp = maxheap.top(); maxheap.pop(); minheap.push(tmp); cout<<"nums2_"<<j<<"_:"<<nums2[j]<<endl; j++; }else{ minheap.push(nums2[j]); int tmp = minheap.top(); minheap.pop(); maxheap.push(tmp); cout<<"nums2_"<<j<<"_:"<<nums2[j]<<endl; j++; } } cout<<"top:"<<maxheap.top()<<"_:"<<minheap.top()<<endl; if(maxheap.size()==minheap.size()) return (double(maxheap.top())+double(minheap.top()))/2; else return minheap.top(); } };