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;
    }
}

 

 

转载于:https://www.cnblogs.com/haoHaoStudyShare/p/7354467.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值