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

快乐安康

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

算法的时间复杂度应该为 O(log (m+n))

复制代码
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    if (nums1.length > nums2.length) {
        return findMedianSortedArrays(nums2, nums1);
    }
    int x = nums1.length;
    int y = nums2.length;
    int low = 0, high = x;
    while (low <= high) {
        int partitionX = (low + high) / 2;
        int partitionY = (x + y + 1) / 2 - partitionX;

        int maxX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
        int maxY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];

        int minX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];
        int minY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];

        if (maxX <= minY && maxY <= minX) {
            if ((x + y) % 2 == 0) {
                return (double) (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;
            } else {
                return (double) Math.max(maxX, maxY);
            }
        } else if (maxX > minY) {
            high = partitionX - 1;
        } else {
            low = partitionX + 1;
        }
    }
    throw new IllegalArgumentException("Input arrays are not sorted.");
}
相关推荐
小和尚敲木头12 分钟前
vue3 vite动态拼接图片路径
javascript
艾利克斯冰31 分钟前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
倒霉蛋小马44 分钟前
Java新特性:record关键字
java·开发语言
我叫黑大帅1 小时前
前端如何竖屏固定视口背景
前端·javascript·面试
折哥的程序人生 · 物流技术专研1 小时前
《Java 100 天进阶之路》第95篇:消息队列基础(RocketMQ/Kafka)(2026版)
java·面试·kafka·rocketmq·java-rocketmq·求职招聘
budingxiaomoli1 小时前
Spring日志
java·开发语言
IT空门:门主1 小时前
Spring 注入三剑客:@Resource、@Autowired、@RequiredArgsConstructor 到底该用哪个?
java·后端·spring
不会敲代码11 小时前
我花了三天时间,终于把 Cookie、XSS、CSRF 和浏览器存储给整明白了
javascript·面试
贩卖黄昏的熊1 小时前
flex 布局快速梳理
开发语言·javascript·css3·html5
swipe1 小时前
Mem0 x Agent 实战系列:分层记忆 + 三路召回,搭建真正可用的长期记忆层
前端·javascript·面试