preface
This problem is actually quite simple, but Leetcode difficulty is defined as difficult. Find the median of two positive ordinal groups
Train of thought
If nums[I]>nums[j],j ++, L ++; if nums[I]>nums[j],j ++,l++; Otherwise i++,l++, I know l is the median. Of course, consider that an array may have already been traversed, and the median has not yet been found, so you have to iterate over the array again.
code
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length = nums1.length + nums2.length;
int i =0,j=0,l=0;
float curLef = -10^6 -1,curRight = -10^6-1;
int indexLeft = (length-1) /2;
int indexRight = length/2;
while(i<nums1.length && j < nums2.length ){
if( nums1[i] >= nums2[j] ){
if (indexLeft == l) curLef = nums2[j];
if (indexRight == l) {curRight = nums2[j];return (curLef + curRight)/2; }
j++;
l++;
}else{
if (indexLeft == l) curLef = nums1[i];
if (indexRight == l) {curRight = nums1[i];return (curLef + curRight)/2; } i++; l++; }}while (i < nums1.length ){
if (indexLeft == l) curLef = nums1[i];
if (indexRight == l) {curRight = nums1[i];return (curLef + curRight)/2; }
i++;
l++;
}
while (j < nums2.length ){
if (indexLeft == l) curLef = nums2[j];
if (indexRight == l) {curRight = nums2[j];return (curLef + curRight)/2; }
j++;
l++;
}
return (curLef + curRight)/2;
}
Copy the code