首页 > 代码库 > 4. Median of Two Sorted Arrays【leetcode】java,算法,中间值

4. Median of Two Sorted Arrays【leetcode】java,算法,中间值

4. Median of Two Sorted Arrays

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 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
题目大意:求中值
实现方法
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        double res=0.00;
        int n=nums2.length;
        //判断非空的情况
        if(nums1==null){
            return res=nums2[n/2];
        }
        int m=nums1.length;
        if(nums2==null){
            return res=nums1[m/2];
        }    
        //建立标志位用于标记此次是奇数还是偶数个数字
        int carry=(m+n)%2;
        //建立标志位,如果为奇数的情况下right即为中间值mid
        int left=(m+n)/2-1;
        int right=(m+n)/2;
        //开通一个m+n的空间其实实际只使用一半,若为节省空间可以采用
        int [] num =new int[m+n];
        int i=m-1,j=n-1;
        int index=m+n-1;

        //将两个数组进行排序(中间值-最后进行排序)
        while(index>left){
            while(i>=0&&j>=0){

                num[index--]=(nums1[i]>nums2[j])?nums1[i--]:nums2[j--];
            }
            while(i>=0){
                num[index--]=nums1[i--];
            }
            while(j>=0){
                num[index--]=nums2[j--];
            }
        }//end
        if(carry>0)
            //奇数位置的中间值
            res =(double)num[right];
        else{
            //偶数位置的中间值
            res=(double)(num[left]+num[right])/2;
        }
        return res;
    }
}

 

4. Median of Two Sorted Arrays【leetcode】java,算法,中间值