Median of Two Sorted Arrays

There are two sorted arraysnums1andnums2of 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 = nums1.length, n = nums2.length, 假设m < n(大于就交换过来)
设min = 0, max = m, i = (min + max)/2, j = (m + n)/2 - i(中位数在[0, (n+m)/2]之间),
比较nums1[i-1],nums[i]和nums2[j-1], nums2[j]
得到正确解的情况是:nums2[j-1] < nums1[i]
得到的结果要分为奇偶讨论.
另外对于其他两种情况:
nums1[i] < nums2[j-1]表明i太小需要将i增大,即修改min = i+1, 这种情况要确保i != m <==> j > 0;
nums1[i-1] > nums2[j]表明i太大需要将i减小,即修改max = i -1, 这种情况要确保i > 0 <==> j < n;
另外需要处理边界情况
当i=0时
max_left = nums2[j-1]
当j=0时
max_left = nums1[i-1]
否则max_left = max(nums1[i-1], nums2[j-1])
当i=m时
min_right = nums2[j]
当j=n时
min_right = nums1[i]
否则
min_right = min(nums1[i], nums2[j])
当数组长度为奇数时:
result = max(nums1[i-1], nums2[j-1])
当数组长度为偶数时:
result = (max_left + min_right )/2;
java代码:

public double findMedianSortedArrays(int[] nums1, int[] nums2) {

    int m=nums1.length,n=nums2.length;

    if(m>n){
        return findMedianSortedArrays(nums2, nums1);
    }

    int mid = (m+n+1)/2;
    int minPos = 0;
    int maxPos = m;
    int pos1 = (maxPos+minPos)/2;
    int pos2 = mid - pos1;
    int num1=0,num2=0;
    
    while(minPos<=maxPos){
        
        if(pos1>0 && nums1[pos1-1]>nums2[pos2]){
            maxPos = pos1-1;
        }else if(pos1 < m && nums1[pos1]

你可能感兴趣的:(Median of Two Sorted Arrays)