LeetCode: Median of Two Sorted Arrays

本文介绍了一种在两个已排序数组中查找中位数的方法。通过比较两个数组的中位数并逐步缩小搜索范围,最终找到精确的中位数。此算法的时间复杂度为O(logn),适用于处理大型数据集。

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

http://leetcode.com/onlinejudge#question_4

metge sort的merge时候比较,o(n+m)

public class Solution {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int A[] = {};
        int B[] = { 1, 2, 3, 4, 5 };
        double c = new Solution().findMedianSortedArrays(A, B);
        System.out.println(c);
    }

    public double findMedianSortedArrays(int A[], int B[]) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int startA = 0;
        int startB = 0;
        int tempS = 0, tempE = 0;
        double end = ((double) A.length + B.length) / 2;
        while (startA + startB < end) {
            if (startA >= A.length) {
                tempS = B[startB];
                startB++;
            } else if (startB >= B.length) {
                tempS = A[startA];
                startA++;
            } else if (A[startA] > B[startB]) {
                tempS = B[startB];
                startB++;
            } else {
                tempS = A[startA];
                startA++;
            }

        }
        if ((A.length + B.length) % 2 == 1) {
            tempE = tempS;

        } else if (startA >= A.length) {
            tempE = B[startB];

        } else if (startB >= B.length) {
            tempE = A[startA];

        } else if (A[startA] > B[startB]) {
            tempE = B[startB];

        } else {
            tempE = A[startA];

        }
        return ((double) tempS + tempE) / 2;

    }
}
View Code

改进:

比较两个数组的中位数

ar1[]和ar2[]为输入的数组
算法过程:
1.得到数组ar1和ar2的中位数m1和m2
2.如果m1==m2,则完成,返回m1或者m2
3.如果m1>m2,则中位数在下面两个子数组中
   a)  From first element of ar1 to m1 (ar1[0...|_n/2_|])
   b)  From m2 to last element of ar2  (ar2[|_n/2_|...n-1])
4.如果m1<m2,则中位数在下面两个子数组中
   a)  From m1 to last element of ar1  (ar1[|_n/2_|...n-1])
   b)  From first element of ar2 to m2 (ar2[0...|_n/2_|])
5.重复上面的过程,直到两个子数组的大小都变成2
6.如果两个子数组的大小都变成2,使用下面的式子得到中位数
   Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2

时间复杂度:O(logn)。

待实现代码。。。

转载于:https://www.cnblogs.com/pengzheng/archive/2013/05/15/3079505.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值