Created
May 9, 2019 13:47
-
-
Save panyan928/a0ab1e37bed6a746326974462957a89c to your computer and use it in GitHub Desktop.
median of two sorted array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
median of two sorted array | |
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 | |
*/ | |
class Solution { | |
public: | |
int Max(int a, int b) | |
{ | |
return a>b?a:b; | |
} | |
int Min(int a,int b) | |
{ | |
return a<b?a:b; | |
} | |
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { | |
int m = nums1.size(); | |
int n = nums2.size(); | |
if(m>n){ | |
vector<int> temp; | |
temp = nums1; | |
nums1 = nums2; | |
nums2 = temp; | |
int temp2 = m; | |
m = n; | |
n = temp2; | |
} | |
if(m==0 and n==1){ | |
return nums2.at(0); | |
} | |
if(m==1 and n==1){ | |
return float(nums1.at(0)+nums2.at(0))/2; | |
} | |
int min = 0, max = m, half = (m+n+1)/2; | |
int middle; | |
while(min<=max){ | |
int i = (min+max)/2; //i,j : the length of left A, B; | |
int j = half - i; | |
if(i < max and nums2.at(j-1) > nums1.at(i)) | |
{ | |
min = i+1; | |
} | |
else if (i>min and nums2.at(j) < nums1.at(i-1)) | |
{ | |
max = i-1; | |
} | |
else // find index | |
{ | |
int maxleft; | |
//理解i的意思,表示A的左边部分有0个,所以左边最大一定是B中 | |
//虽然n>m, 但是j也存在边界情况,当两个数组长度相等时,需要判断j==0或者n | |
if(i==0){ maxleft = nums2.at(j-1);} // 这里A[i]一定比B[j-1]大,所以A[i]应该在右半部分,如果A[i]< B[j-1] 会满足条件1,使i==1 | |
else if (j==0) maxleft=nums1.at(i-1); | |
else{ | |
maxleft = Max(nums2.at(j-1), nums1.at(i-1)); | |
} | |
if ((m+n)%2 == 1) return maxleft; | |
int minright; | |
if(i==m){minright = nums2.at(j);} | |
else if (j==n) minright = nums1.at(i); | |
else minright = Min(nums2.at(j), nums1.at(i)); | |
return double(minright+maxleft)/2; | |
} | |
} | |
return 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment