1、一提到中位數就要考慮數組的個數是奇數還是偶數;
2、涉及到排序數組的求和、求中位數這類的問題都要想到用二分法的思想;
題目:
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
找到兩個數組所組成的數的中位數。
思路:
1、考慮特殊情況,即有一個數組爲空、每個數組只有一個元素;
2、判斷m+n是奇數還是偶數,然後進行遞歸;
3、利用二分的思路,一半一半的進行刪除,令
int pa=min(k/2,n);
int pb=k-pa;
用k的一半進行比較,如果前一半比較小,則肯定不符合條件,則遞歸find(nums1[pa],m-pa,nums2,n,k-pa)
,反之如果pb比較小則這部分肯定也不符合條件,遞歸find(nums1,m,nums2[pb],n-pb,k-pb)
;
代碼:
class Solution {
public:
double find(vector<int> & nums1,int m,vector<int> & nums2,int n,int k)
{
if(m<n) return find( nums1,n,nums2,m,k);
if(n==0) return nums2[k-1];
if(k==1) return min(nums1[0],nums2[0]);
int pa=min(k/2,n);
int pb=k-pa;
if(nums1[pa-1]>nums2[pb-1]) return find(nums1,m,nums2+pb,n-pb,k-pb);
else if(nums1[pa-1]<nums2[pb-1]) return find(nums1+pa,m-pa,nums2,n,k-pa);
else return nums1[pa-1];
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m=nums1.size();
int n=nums2.size();
int total=n+m;
if(total%2)
return find(nums1,m,nums2,n,total/2+1);
else return (find(nums1,m,nums2,n,total/2)+find(nums1,m,nums2,n,total/2+1))/2;
}
};
但是出現瞭如下的錯誤,不知道怎麼改,希望大家能幫助改正;
Line 10: no matching function for call to ‘Solution::find(std::vector&, int&, __gnu_cxx::__alloc_traits