【寻找两个正序数组的中位数】

本文题目来源力扣题库
力扣地址

给定两个大小分别为 m 和 n 的正序(从小到大)数组nums1 和nums2。请你找出并返回这两个正序数组的 中位数 。

    /**
     * 给定两个大小分别为 m 和 n 的正序(从小到大)数组nums1 和nums2。请你找出并返回这两个正序数组的 中位数 。
     *
     * 算法的时间复杂度应该为 O(log (m+n)) 。
     *
     * @param args
     */
    public static void main(String[] args) {
		int[] num1 = new int[]{2,4,7};
        int[] num2 = new int[]{1,3,5,6};
        System.out.println(findMedianSortedArrays(num1,num2));
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] temp = new int[nums1.length+nums2.length];
        int tempIndex = 0;
        int l1 = nums1.length;
        int l2 = nums2.length;
        int[] temp1;
        int[] temp2;
        // 设置始终让最长的数组为 temp1
        if(l1 > l2){
            temp1 = nums1;
            l1 = nums1.length;
            temp2 = nums2;
            l2 = nums2.length;
        }else {
            temp1 = nums2;
            l1 = nums2.length;
            temp2 = nums1;
            l2 = nums1.length;
        }
        // 初始化移动指针
        int t1 = 0,t2 = 0;
        while(t1 < l1 || t2 < l2){
            // temp1 数据全部取出只取 temp2
            if(t1 == l1){
                int k = temp2[t2];
                temp[tempIndex++] = k;
                t2++;
                continue;
            }
            // temp2 数据全部取出只取 temp1
            if(t2 == l2){
                int j = temp1[t1];
                temp[tempIndex++] = j;
                t1++;
                continue;
            }
            // temp1 和 temp2 全部有数据则一起取出做对比
            int j = temp1[t1];
            int k = temp2[t2];
            if(j < k){
                temp[tempIndex++] = j;
                t1++;
            } else if (j > k) {
                temp[tempIndex++] = k;
                t2++;
            }else{
                temp[tempIndex++] = j;
                temp[tempIndex++] = k;
                t1++;;t2++;
            }
        }
        double res = 0;
        if(tempIndex % 2 == 0){
            res = (temp[tempIndex/2-1]+temp[tempIndex/2])/2D;
        }else {
            res = temp[tempIndex/2];
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值