Median of Two Sorted Arrays
Problem 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)).
Example:
nums1 = [1, 3]
nums2 = [2]The median is 2.0
Example:
nums1 = [1, 2]
nums2 = [3, 4]The median is (2 + 3)/2 = 2.5
Algorithmic thinking
It mainly uses the idea of divide and conquer, which is similar to Reverse Pairs.
1. The Title asks me to find the median of two arranged sequences A and B. The lengths of the two sequences are m and n, respectively. The number of k= (m+n) in the two sequences is also required.
2. We assume that P and Q are the medians of A and B respectively (this is easy to find), and then compare the sizes of P and q. If P < q, the numbers before P in A are not the medians of the two sequences. We can "discard" half of the number on the A side. Now the problem becomes finding the k_p number of the remaining numbers.
3. By throwing away half of the number of one sequence each time, we can get the solution of the problem quickly.
4. We should pay attention to several border issues. (1) If A or B is empty, just return A[k_1] or B [see_1]. (2) If K is 1, return the smaller number in A[0] and B[0]. (3) If A[k/2_1]=B[k/2_1], return to one of them at will.
Algorithm code
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int i = 0;
int j = 0;
int b = (len1 + len2)/2 - (len2 + len1 + 1)%2;
int a = 0;
if(len1 != 0 && len2 !=0){
while(a != b){
if(nums1[i] <= nums2[j]){
if(i + 1 < len1)
i++,a++;
else{
break;
}
}
else if(nums1[i] > nums2[j]){
if(j + 1 < len2)
j++,a++;
else{
break;
}
}
}
if(a != b){
a = a + 1;
if(i + 1 < len1){
if((len2 + len1)%2 == 1){
return (double)nums1[i + b - a];
}
else
return ((double)nums1[i + b - a] + (double)nums1[i + b - a + 1])/2;
}
else{
if((len2 + len1)%2 == 1){
return (double)nums2[j + b - a];
}
else{
return ((double)nums2[j + b - a] + (double)nums2[j + b - a + 1])/2;
}
}
}
else{
if((len2 + len1)%2 == 1){
return (double)nums1[i] < (double)nums2[j]?(double)nums1[i]:(double)nums2[j];
}
else{
double tmp = ((double)nums1[i] + (double)nums2[j])/2;
double tmp1,tmp2;
if(i + 1 < len1){
double tmp11 = ((double)nums1[i] + (double)nums1[i+1])/2;
double tmp12 = ((double)nums1[i + 1] + (double)nums2[j])/2;
tmp1 = tmp11 < tmp12 ? tmp11:tmp12;
}
else
tmp1 = tmp;
if(j + 1 < len2){
double tmp21 = ((double)nums2[j + 1] + (double)nums2[j])/2;
double tmp22 = ((double)nums1[i] + (double)nums2[j+1])/2;
tmp2 = tmp21 < tmp22 ? tmp21:tmp22;
}
else
tmp2 = tmp;
tmp1 = tmp1 < tmp2 ? tmp1:tmp2;
tmp = tmp < tmp1?tmp:tmp1;
return tmp;
}
}
}
else if(len1 == 0){
if(len2%2 == 1){
return (double)nums2[len2/2];
}
else
return ((double)nums2[len2/2] + (double)nums2[len2/2 - 1])/2;
}
else{
if(len1%2 == 1){
return (double)nums1[len1/2];
}
else
return ((double)nums1[len1/2] + (double)nums1[len1/2 - 1])/2;
}
}
};