[LeetCode]4.寻找两个有序数组的中位数

题目

在这里插入图片描述

自己的解法

   public double findMedianSortedArrays(int[] nums1, int[] nums2) {
       int[] nums = new int[nums1.length + nums2.length];
       for(int i =0; i < nums1.length; i++){
           nums[i] = nums1[i];
       } 
       for(int i = 0; i < nums2.length; i++){
           nums[nums1.length + i] = nums2[i];
       }
       Arrays.sort(nums);
       if(nums.length % 2 != 0){
           return nums[nums.length / 2];
       }else{
           return (nums[nums.length/2]+(nums[nums.length/2-1]))/2.0;
       }
    }
}

二分查找

O(log(m+n))

class Solution {
    public double findMedianSortedArrays(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        if(m > n){
            //交换两个数组的顺序
            int[] tmp = A;A = B;B = tmp;
            int temp = m;m = n; n = temp; 
        }
        int iMin = 0, iMax = m, k = (m + n + 1) / 2;
        //二分查找i边界
        while(iMin <= iMax){
            int i = (iMin + iMax)/2;
            int j = k - i;
            if(i < iMax && B[j-1] > A[i]){
                iMin = i + 1;
            }else if (i > iMin && A[i-1] > B[j]){
                iMax = i - 1;
            }else{
                int maxLeft = 0;
                if(i == 0){ maxLeft = B[j - 1];}
                else if(j == 0){ maxLeft = A[i - 1];}
                else {maxLeft = Math.max(A[i-1],B[j-1]);}
                if( (m + n) % 2 == 1 ){return maxLeft;}
                int minRight = 0;
                if(i == m){ minRight = B[j];}
                else if(j == n){ minRight = A[i];}
                else {minRight = Math.min(A[i],B[j]);}

                return (maxLeft + minRight)/2.0;
                }
        }
        return 0.0;
    }
}

在这里插入图片描述

posted @ 2019-11-21 21:13  消灭猕猴桃  阅读(59)  评论(0编辑  收藏  举报