leetcode-尋找兩個正序陣列的中位數
阿新 • • 發佈:2021-07-14
\
此題與之前在一個數組中找中位數類似,可以在基礎上修改。
不過在入堆的時候需要對兩個陣列大小元素進行判斷,小的入堆。
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(); } };