題目地址 : https://leetcode.com/problems/median-of-two-sorted-arrays/?tab=Description
題目描述 : 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)).
我的代碼 :
/*
當m+n是奇數時,中位數即是低(m+n+1)/2大的數;當m+n是偶數時,中位數是第(m+n)/2和(m+n)/2+1大的數的平均。由此只需求第k大的數的函數。
不妨設兩個數組的長度有n>=m,顯然當m=0時直接可得,當k=1時爲兩個數組第一個數的最小者,而當m>0且k>1時,則令i=min(m,k/2),顯然0<i<k;令j=k-i;比較數組n的第j個數與數組m的第i個數,當前者更大時,第k大數肯定不在數組m的前i個數中,去掉這i個數,求新數組的第k-i大的數;否則可去掉數組n的前j個數,求新數組的第k-j大的數。由於數組長度漸短,且k以1/2的階遞減,所以複雜度爲O(log(m+n))。
*/
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n=nums1.size();
int m=nums2.size();
if((m+n)%2==1) return find_kth_of_sorted_arrays(nums1.begin(),nums1.size(),nums2.begin(),nums2.size(),(m+n+1)/2);
int a=find_kth_of_sorted_arrays(nums1.begin(),nums1.size(),nums2.begin(),nums2.size(),(m+n)/2);
int b=find_kth_of_sorted_arrays(nums1.begin(),nums1.size(),nums2.begin(),nums2.size(),(m+n+2)/2);
return (a+b)/2.0;
}
int find_kth_of_sorted_arrays(vector<int>::iterator nums1,int n,vector<int>::iterator nums2,int m,int k){
//求第k大的數
if(m>n) return find_kth_of_sorted_arrays(nums2,m,nums1,n,k);
if(m==0) return nums1[k-1];
if(k==1) return nums1[0]<nums2[0]?nums1[0]:nums2[0];
int i=m<k/2?m:k/2;
int j=k-i;
if(nums1[j-1]<nums2[i-1]) return find_kth_of_sorted_arrays(nums1+j,n-j,nums2,i,k-j);
else return find_kth_of_sorted_arrays(nums1,j,nums2+i,m-i,k-i);
}
};