4. Median of Two Sorted Arrays
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)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
思路:很容易想到两个排序数组合并为一个排序数组,然后O(1)的时间可以拿到中位数,但是合并的时间复杂度为O(m+n),不合题意。
考虑中位数的本质,把两个数组分成两个部分,记为A,B,分界点为i,j。若保证n>=m,则有j=(m+n+1)/2-i;只需要找到一个i,使
A[i-1]<=B[j]
B[j-1]<=A[i]
就成功地将两个数组分成了两部分,时间复杂度为O(log(m+n)),并能在O(1)的时间拿到中位数
1 class Solution { 2 public: 3 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 4 int m=nums1.size(); 5 int n=nums2.size(); 6 vector<int> *A=&nums1; 7 vector<int> *B=&nums2; 8 if(m>n){//始终保证n>=m 9 vector<int> *tmp=A; A=B; B=tmp; 10 int val=m; m=n; n=val; 11 } 12 int halfLen=(m+n+1)/2; 13 int left=0, right=m; 14 while(left<=right) 15 { 16 int i=(left+right)/2; 17 int j=halfLen-i; 18 if(i>left && (*A)[i-1]>(*B)[j])right=i-1;//注意限定条件i>left 19 else if(i<right && (*B)[j-1]>(*A)[i])left=i+1; 20 else{ 21 int maxLeft=0; 22 if(i==0)maxLeft=(*B)[j-1]; 23 else if(j==0)maxLeft=(*A)[i-1]; 24 else{ 25 maxLeft=(*A)[i-1]; 26 if(maxLeft<(*B)[j-1])maxLeft=(*B)[j-1]; 27 } 28 if((m+n) & 1)return maxLeft;//如果m+n为奇数,直接返回 29 int minRight=0; 30 if(i==m)minRight=(*B)[j]; 31 else if(j==n)minRight=(*A)[i]; 32 else{ 33 minRight=(*A)[i]; 34 if(minRight>(*B)[j])minRight=(*B)[j]; 35 } 36 return (maxLeft+minRight)*1.0/2; 37 } 38 } 39 return -1; 40 } 41 };