【LeetCode解答四】Median of Two Sorted Arrays问题Java解答

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

这道题没有什么理解上的问题,就是给出两个排好序的数组,要求求出两个数组从小到大的中间值,但是好像是要求时间复杂度为O(log(M+N)),其实我自己写的时候只是考虑最简单的算法,没有算时间复杂度…所以我的答案的时间复杂度是多少我也不知道。
我的做法就是将两个数组按照从小到大的顺序合并成一个数组,再求数组中间值就简单了,但是代码的冗长我自己都难以直视,一会儿看看别的大牛的博客看看能不能做一些优化,运行时间应该还算过得去。

double result = 0.0;
        //定义最终数组长度
        int sum = nums1.length + nums2.length;
        int[] nums3 = new int[sum];
        //若其中一数组为空,则最终数组直接等于另一个数组
        if(nums1.length == 0){
            nums3 = nums2;
        }
        if (nums2.length == 0){
            nums3 = nums1;
        }
        int i = 0;
        int j = 0;
        //以flag作为标识符
        int flag1;
        int flag2;
        //循环条件:两数组均不为空且任一指针不到数组尽头
        while ((nums1.length!=0 && nums2.length != 0) && (i < nums1.length || j < nums2.length)){
            //若指针到数组尽头 为防止IndexOutOfBoundsException,对标识符做减一处理
            if (i >= nums1.length){
                flag1 = i-1;
            } else{
                flag1 = i;
            }
            if (j >= nums2.length){
                flag2 = j-1;
            } else{
                flag2 = j;
            }
            //若任一指针没有到数组尽头,则向最终数组中填入数字
            if (!(i + j == sum)){
                nums3[i+j] = Math.min(nums1[flag1],nums2[flag2]);
            }
            //若数组一的数字比较小
            if (nums1[flag1] < nums2[flag2]){
                if(i < nums1.length - 1){
                    i ++;
                } else{
                    //若数组1到了尽头,则使数组1的最大值比数组2大
                    nums1[nums1.length - 1] = nums2[nums2.length - 1] + 1;
                    i ++;
                }
            } else{
                if(j < nums2.length - 1){
                    j ++;
                } else{
                    nums2[nums2.length - 1] = nums1[nums1.length - 1] + 1;
                    j ++;
                }
            }
        }
//        System.out.println(Arrays.toString(nums3));

        int num = sum / 2;
        if (nums3.length % 2 ==0){
            double num1 = nums3[num - 1];
            double num2 = nums3[num];
            result = (num1 + num2) / 2;
        } else{
            result = nums3[num];
        }
        return result;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值