LeetCode-每日一道算法题

  1. 寻找两个正序数组的中位数

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

示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2

示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

示例 3:
输入:nums1 = [0,0], nums2 = [0,0]
输出:0.00000

示例 4:
输入:nums1 = [], nums2 = [1]
输出:1.00000

示例 5:
输入:nums1 = [2], nums2 = []
输出:2.00000

代码:

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //思路:新建一个数组,长度为两数组总长度的一半 + 1(中位数),
        //中位数就是新数组的最后一个值或者是倒数两个值的和的平均数
        //新增变量,保存nums1和nums2的索引,比较两数组的值
        int index1 = 0;
        int index2 = 0;
        int length1 = nums1.length;
        int length2 = nums2.length;
        double result = 0.0;
        //两个数组长度都为0,直接返回0
        if(length1 == 0 && length2 == 0){
            return result;
        }
        //新数组
        int newLength = ((length1 + length2) / 2) + 1;
        int[] newArray = new int[newLength];
        for(int i = 0; i < newLength; i++){
            int num1;
            int num2;
            //数组1长度为0或者下标移动至尾部,直接计算数组2的中位数
            if(length1 == 0 || index1 >= length1){
                newArray[i] = nums2[index2];
                index2++;
                continue;
            }else {
                num1 = nums1[index1];
            }
            //数组2长度为0或者下标移动至尾部,直接计算数组1的中位数
            if(length2 == 0 || index2 >= length2){
                newArray[i] = nums1[index1];
                index1++;
                continue;
            }else {
                num2 = nums2[index2];
            }
            //判断两个值大小,小的保存到新数组,同时索引后移
            if(num1 > num2){
                newArray[i] = num2;
                index2++;
            }else{
                newArray[i] = num1;
                index1++;
            }
        }
        result = (length1 + length2) % 2 == 0 ? (newArray[newLength - 1] + newArray[newLength - 2]) / 2.0:newArray[newLength - 1];
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值