leetcode-004 Median of Two Sorted Arrays

本文介绍了一种高效算法,用于查找两个已排序数组的中位数,整体运行时间复杂度为O(log(m+n))。该算法首先合并两个数组,然后找到合并后数组的中位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

P004 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)).

思路分析

最简单的做法就是将两个数组先合并,再找中间位置

  • 先循环一次将两个数组合并
  • 检测是不是有没合并的遗漏的元素,遗漏的是最大的,放到最后
  • 取新数组的中间位置

代码

java

public class Solution004 {

    private double getMedian(int a[]) {
        if ((a.length & 1) == 1)// 奇数
            return a[a.length / 2];
        else
            return 1.0 * (a[a.length / 2] + a[a.length / 2 - 1]) / 2.0;
    }

    public double findMedianSortedArrays(int A[], int B[]) {
        if (A.length == 0)
            return getMedian(B);
        if (B.length == 0)
            return getMedian(A);

        int arr[] = new int[A.length + B.length];
        int i = 0;
        int j = 0;
        int k = 0;

        // 合并
        while (k < arr.length && i < A.length && j < B.length) {
            if (A[i] <= B[j] && i < A.length)
                arr[k++] = A[i++];
            else
                arr[k++] = B[j++];
        }

        // 处理剩余
        while (i < A.length) {
            arr[k++] = A[i++];
        }

        // 处理剩余
        while (j < B.length) {
            arr[k++] = B[j++];
        }

        return getMedian(arr);
    }
}

python

class Solution004(object):
    def getMedian(self, arr):
        l = len(arr)
        if ((l & 1) == 1):
            return arr[l / 2]
        else:
            return 1.0 * (arr[l / 2] + arr[l / 2 - 1]) / 2.0


    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """

        if len(nums1) == 0:return self.getMedian(nums2)
        if len(nums2) == 0:return self.getMedian(nums1)

        k = j = i = 0;
        l1 = len(nums1);l2 = len(nums2)
        total = l1 + l2
        arr = [0] * total;

        while(k < total and i < l1 and j < l2):
            if nums1[i] < nums2[j]:
                arr[k] = nums1[i]
                i += 1
            else:
                arr[k] = nums2[j]
                j += 1
            k += 1

        while i < l1:
            arr[k] = nums1[i]
            i += 1
            k += 1


        while j < l2:
            arr[k] = nums2[j]
            j += 1
            k += 1

        return self.getMedian(arr)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值