LeetCode - Median of Two Sorted Arrays

本文介绍了一个算法问题,即找到两个已排序数组的中位数,并提供了一个符合O(log(m+n))时间复杂度要求的解决方案。通过比较两个数组的元素并逐步填充新数组的方式,最终求出中位数。
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

 

题目要求time complexity 是O(log (m+n)), 先归并排序也是不可行的, 时间复杂度为O(m+n)

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
        int l1 = nums1.length;
        int l2 = nums2.length;
        int i1 = 0;
        int i2 = 0;
        int i = 0;
        int[] nums = new int[l1+l2];
        while(i1 < l1 && i2 <l2){
            int num1 = nums1[i1];
            int num2 = nums2[i2];
            if(num1 < num2){
                nums[i] = num1;
                i1++;
            }
            else{
                nums[i] = num2;
                i2++;
            }
            i++;
        }
        if(i1 == l1){
            while(i2 < l2){
                nums[i]=nums2[i2];
                i2++;
                i++;
            }
        }
        else if(i2 == l2){
            while(i1 <l1){
                nums[i] = nums1[i1];
                i1++;
                i++;
            }
        }
        
        //find median
        if(i % 2 != 0){
            return (double)nums[i/2];
        }
        else{
            return ((double)nums[i/2-1] + (double)nums[i/2])/2;
        }
    }
}

  

转载于:https://www.cnblogs.com/incrediblechangshuo/p/9065502.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值