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.");
}
相关推荐
不吃香菜学java11 分钟前
Redis的java客户端
java·开发语言·spring boot·redis·缓存
captain37633 分钟前
事务___
java·数据库·mysql
北漂Zachary44 分钟前
四大编程语言终极对比
android·java·php·laravel
小江的记录本1 小时前
【网络安全】《网络安全常见攻击与防御》(附:《六大攻击核心特性横向对比表》)
java·网络·人工智能·后端·python·安全·web安全
这儿有一堆花1 小时前
前端三件套真的落后了吗?揭开现代 Web 开发的底层逻辑
前端·javascript·css·html5
白羊by1 小时前
YOLOv1~v11 全版本核心演进总览
深度学习·算法·yolo
.Cnn1 小时前
JavaScript 前端基础笔记(网页交互核心)
前端·javascript·笔记·交互
醉酒的李白、2 小时前
Vue3 组件通信本质:Props 下发,Emits 回传
前端·javascript·vue.js
嗑嗑嗑瓜子的猫2 小时前
Java!它值得!
java·开发语言
墨尘笔尖3 小时前
最大最小值降采样算法的优化
c++·算法