LeetCode:68.寻找两个正序数组的中位数

目录

1.寻找两个正序数组的中位数


1.寻找两个正序数组的中位数

cpp 复制代码
class Solution {
public:
    int getMinKth(vector<int>& nums1, vector<int>& nums2, int k)
    {
        int m = nums1.size(), n = nums2.size();
        int index1 = 0, index2 = 0;

        while(true)
        {
            if(index1 == m) return nums2[index2 + k - 1];
            if(index2 == n) return nums1[index1 + k - 1];
            if(k == 1) return min(nums1[index1], nums2[index2]);

            int newIndex1 = min(index1 + k / 2 - 1, m - 1);
            int newIndex2 = min(index2 + k / 2 - 1, n - 1);
            int sum1 = nums1[newIndex1];
            int sum2 = nums2[newIndex2];

            if(sum1 <= sum2)
            {
                k -= newIndex1 - index1 + 1;
                index1 = newIndex1 + 1;
            }
            else
            {
                k -= newIndex2 - index2 + 1;
                index2 = newIndex2 + 1;
            }
        }
    }

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
    {
        int length = nums1.size() + nums2.size();
        if(length % 2 == 1)
            return getMinKth(nums1, nums2, (length + 1) / 2);
        else
            return (getMinKth(nums1, nums2, length / 2) + getMinKth(nums1, nums2, length / 2 + 1)) / 2.0;
    }
};
相关推荐
2501_945424802 分钟前
高性能计算资源调度
开发语言·c++·算法
Tisfy9 分钟前
LeetCode 1594.矩阵的最大非负积:动态规划O(mn)
leetcode·矩阵·动态规划·dp
2301_7765087210 分钟前
C++中的组合模式变体
开发语言·c++·算法
Frostnova丶13 分钟前
LeetCode 1594.矩阵中最大的非负乘积
算法·leetcode·矩阵
We་ct13 分钟前
LeetCode 162. 寻找峰值:二分高效求解
前端·算法·leetcode·typescript·二分·暴力
丶小鱼丶13 分钟前
数据结构和算法之【二叉树】
java·数据结构·算法
hanlin0313 分钟前
刷题笔记:力扣第38题-外观数列
算法·leetcode
2301_7938046916 分钟前
模板代码安全性增强
开发语言·c++·算法
测试_AI_一辰17 分钟前
Agent & RAG 测试工程笔记 13:RAG检索层原理拆解:从“看不懂”到手算召回过程
人工智能·笔记·功能测试·算法·ai·ai编程
干啥啥不行,秃头第一名19 分钟前
C++中的观察者模式
开发语言·c++·算法