力扣HOT100 - 4. 寻找两个正序数组的中位数

解题思路:

两个数组合并,然后根据奇偶返回中位数。

java 复制代码
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int[] nums = new int[m + n];
        if (m == 0) {
            if (n % 2 == 0) return (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
            else return nums2[n / 2];
        }
        if (n == 0) {
            if (m % 2 == 0) return (nums1[m / 2 - 1] + nums1[m / 2]) / 2.0;
            else return nums1[m / 2];
        }

        int cnt = 0;
        int i = 0, j = 0;
        while (cnt != (m + n)) {
            if (nums1[i] < nums2[j]) nums[cnt++] = nums1[i++];
            else nums[cnt++] = nums2[j++];

            if (i == m) {
                while (j != n)
                    nums[cnt++] = nums2[j++];
            }
            if (j == n) {
                while (i != m)
                    nums[cnt++] = nums1[i++];
            }
        }
        if (cnt % 2 == 0) return (nums[cnt / 2 - 1] + nums[cnt / 2]) / 2.0;
        else return nums[cnt / 2];
    }
}
相关推荐
karry_k16 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k16 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
vibecoding日记17 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213819 小时前
Verilog参数化游程编码RLE模块
算法
SamDeepThinking19 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
望易20 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
她的男孩1 天前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
复杂网络1 天前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python