4.Median of Two Sorted Arrays Leetcode Python

[ LeetCode ] 4. Median of Two Sorted Arrays (C++ & Python) 题目:4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log ... 阅读详情
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

这题的一种O(m+n)的解法是mergesort的一步,依次比较两者的大小,将得到的解放到新的item里面。

最后再取出median


class Solution:
    # @return a float
    def findMedianSortedArrays(self, A, B):
        item=[]
        while len(A)>0 and len(B)>0:
            item.append(A.pop(0) if A[0]<=B[0] else B[0])
        while len(A)>0:
            item.append(A.pop(0))
        while len(B)>0:
            item.append(B.pop(0))
        if len(item)%2==1:
            return item[len(item)/2]
        else: 
            return (item[len(item)/2]+item[len(item)/2-1])/2
            
        
另外一种解法是来自
http://blog.csdn.net/zxzxy1988/article/details/8587244

主题思想是每次比较A和B的各一半 

如果A[half]<B[half]  中值会在 A剩下的一半和B中产生

反之 在A和B剩下的一半产生。

如果相等就刚刚好返回A[half]

Assume that the number of elements in A and B are both larger than k/2, and if we compare the k/2-th smallest element in A(i.e. A[k/2-1]) and the k-th smallest element in B(i.e. B[k/2 - 1]), there are three results:
(Becasue k can be odd or even number, so we assume k is even number here for simplicy. The following is also true when k is an odd number.)
A[k/2-1] = B[k/2-1]
A[k/2-1] > B[k/2-1]
A[k/2-1] < B[k/2-1]
if A[k/2-1] < B[k/2-1], that means all the elements from A[0] to A[k/2-1](i.e. the k/2 smallest elements in A) are in the range of k smallest elements in the union of A and B. Or, in the other word, A[k/2 - 1] can never be larger than the k-th smalleset element in the union of A and B.


Why?
We can use a proof by contradiction. Since A[k/2 - 1] is larger than the k-th smallest element in the union of A and B, then we assume it is the (k+1)-th smallest one. Since it is smaller than B[k/2 - 1], then B[k/2 - 1] should be at least the (k+2)-th smallest one. So there are at most (k/2-1) elements smaller than A[k/2-1] in A, and at most (k/2 - 1) elements smaller than A[k/2-1] in B.So the total number is k/2+k/2-2, which, no matter when k is odd or even, is surly smaller than k(since A[k/2-1] is the (k+1)-th smallest element). So A[k/2-1] can never larger than the k-th smallest element in the union of A and B if A[k/2-1]<B[k/2-1];
Since there is such an important conclusion, we can safely drop the first k/2 element in A, which are definitaly smaller than k-th element in the union of A and B. This is also true for the A[k/2-1] > B[k/2-1] condition, which we should drop the elements in B.
When A[k/2-1] = B[k/2-1], then we have found the k-th smallest element, that is the equal element, we can call it m. There are each (k/2-1) numbers smaller than m in A and B, so m must be the k-th smallest number. So we can call a function recursively, when A[k/2-1] < B[k/2-1], we drop the elements in A, else we drop the elements in B.




We should also consider the edge case, that is, when should we stop?
1. When A or B is empty, we return B[k-1]( or A[k-1]), respectively;
2. When k is 1(when A and B are both not empty), we return the smaller one of A[0] and B[0]
3. When A[k/2-1] = B[k/2-1], we should return one of them


In the code, we check if m is larger than n to garentee that the we always know the smaller array, for coding simplicy.


class Solution:
    # @return a float
    def findk(self,A,m,B,n,k):
        if m>n:
            return self.findk(B,n,A,m,k)
        if m==0:
            return B[k-1]
        if k==1:
            return min(A[0],B[0])
        pa=min(k/2,m)
        pb=k-pa
        if A[pa-1]<B[pb-1]:
            return self.findk(A[pa:],m-pa,B,n,k-pa)
        elif A[pa-1]>B[pb-1]:
            return self.findk(A,m,B[pb:],n-pb,k-pb)
        else:
            return A[pa-1]
        
    def solve(self,A,m,B,n):
        m=len(A)
        n=len(B)
        total=m+n
        if total%2==1:
            return self.findk(A,m,B,n,total/2+1)
        else:
            return (self.findk(A,m,B,n,total/2+1)+self.findk(A,m,B,n,total/2))/2.0
            
    def findMedianSortedArrays(self, A, B):
        m=len(A)
        n=len(B)
        result=self.solve(A,m,B,n)
        return result
            



使用Python进行核磁数据预处理 随着医学与人工智能技术的快速崛起,伴随算法算力、数据等关键要素的积累和突破,人工智能技术在精准医学领域的科研应用也随之飞快增长,相关科研成果和学术论文数量逐年激增,医学影像人工智能涉及的技术如图像分割、病灶识别、病灶自动勾画、影像组学、深度学习模型构建和临床信息解析越来越趋于分析流程化,模块化,帮助越来越多的医生在临床科研实践中获得突破性的进展。根据具体的应用和数据类型,你可能需要调整或添加额外的步骤。对于更高级的处理,如图像分割或NMR数据的复杂处理,你可能需要查阅更专业的文献或使用更专业的软件工具。 阅读详情

相关推荐

2024年捡垃圾指南:E5 V3/V4服务器CPU怎么选?从游戏多开到深度学习,附华南X99主板搭配清单

本文详细解析2024年E5 V3/V4服务器CPU的选购策略,涵盖游戏多开、深度学习等多种应用场景。通过对比E5 V3与V4系列的制程、功耗及性能差异,提供高性价比的CPU型号推荐及华南X99主板搭配方案,帮助用户在有限预算下打造高效能工作站。

weixin_42549451的博客 1644

【LeetCode】4. Median of Two Sorted Arrays(Python)

Problem 有两个排序的数组nums1和nums2分别为m和n。 找到两个排序数组的中位数。总运行时间复杂度应为O(log(m + n))。 您可以假设nums1和nums2 不能都为空。 例1: nums1 = [1,3] nums2 = [2] 中位数是2.0 例2: nums1 = [1,2] nums2 = [3,4] 中位数为(2 + 3)/ 2 = 2.5 Algorithmi...

E.W的博客 890

Stable Diffusion跑图总爆显存?别急着换显卡,试试这个PYTORCH_CUDA_ALLOC_CONF参数调优

本文深入解析了Stable Diffusion运行中常见的显存不足问题,特别是由显存碎片化导致的假性OOM现象。通过详细讲解PYTORCH_CUDA_ALLOC_CONF参数中的max_split_size_mb设置技巧,提供了一套完整的显存优化方案,帮助用户在无需升级硬件的情况下显著提升AI绘画的稳定性与效率。

weixin_42524100的博客 353

leetcode 4. Median of Two Sorted Arrays 解法 python

一.问题描述 There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assumenum...

CSerwangjun的博客 1545

Gemini 2.5 Pro国内免魔法直连教程:5分钟搞定专业级PPT图表(附折线图/柱状图案例)

本文详细介绍了如何利用Gemini 2.5 Pro快速生成专业级PPT图表,包括折线图和柱状图等常见商业图表。通过自然语言交互和智能图表生成功能,用户可以在5分钟内完成数据可视化,大幅提升工作效率。文章还提供了实战案例和高级技巧,帮助用户轻松应对各种商业场景需求。

weixin_30733003的博客 463

【无线通信】射频杂散(RF Spurious Emissions)

射频杂散(RF Spurious Emissions)是指在无线通信系统中,除了在指定频率范围内的预期信号之外,任何不需要的或非预期的射频信号。这些杂散信号可能会干扰其他通信系统,降低系统性能,并违反无线电通信法规。射频杂散通常包括谐波、次谐波、互调产物和其他非线性失真所产生的信号。

qq_38801607的博客 5451

LeetCode 4. Median of Two Sorted Arrays Python3

LeetCode 4. Median of Two Sorted Arrays Python3 Description 点击查看题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run t...

与你的博客 419

STM32通过ESP8266连接机智云APP(第二讲,烧录固件并测试)

今天与大家分享STM32通过ESP8266连接机智云APP,并完成数据的上传下发第二讲。带大家一起烧录机智云固件到ESP8266并且将其通过机智云串口助手与APP进行测试。

qq_63267523的博客 1427

[LeetCode] 4. Median of Two Sorted Arrays(Python)

[LeetCode] 4. Median of Two Sorted Arrays(Python)1. 题目2. 题目理解3. 代码实现 1. 题目 Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1:

qq_35029666的博客 933

五、实战pxe安装ubuntu 22.04 软raid1(实际生产pxe配置)

这段配置文件是一个cloud-init的自动安装配置,用于自动化部署Ubuntu服务器操作系统。它定义了从系统身份、键盘布局、区域设置到磁盘分区和RAID配置的一系列设置,并且包含了在安装过程的最后阶段执行的一些命令。基础设置version: 1指定了autoinstall配置文件的版本。source定义了安装源,这里是ubuntu-server。identity设置了主机名(hostname)、用户(username)和密码(password注意这里的密码是经过加密的。键盘与语言设置。

jundao1997的专栏 1004

关于Sybase ASE数据库的license以及试用版过期的问题的解决方案

当用户从Sybase官网上下载了ASE15.0.2以后,如果选择了安装Express Edition或者Developer Edition,基本上不会碰到什么问题,除了有些功能受限以下。 但大多数可能选择了Enterprise Edition for Evaluation类型,即企业版试用。都会碰到这样的问题,即一个月以后,license过期,无法启动server。于是很郁闷,可能大部分人,会选...

iihero@CSDN 794

leetcode 4. Median of Two Sorted Arrays的思路与python实现

思路 基本只能靠背。边缘条件太恶心了... 代码 class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m, n = len(nums1), len(nums2) if m > n: # 上面的要小一点...

qq_35175413的博客 299

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

LeetCode 4.Median of Two Sorted Arrays (Python)

4. Median of Two Sorted Arrays(Python)两个排序数组的中位数

iwanthn的博客 515

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Leetcode 4.Median of Two Sorted Arrays with Python

class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ m = len...

dxcve的博客 172

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

LeetCode:4. Median of Two Sorted Arrays - Python

问题描述: 4. 寻找两个有序数组的中位数 给定两个大小为m和n的有序数组nums1和nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为O(log(m + n))。 你可以假设nums1和nums2不会同时为空。 示例 1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 示例 2: nums1 = [1, 2] nums2 = [3, 4] ...

Growth Diary 2696

【LeetCode 4】Median of Two Sorted Arrays(Python)

Problem: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume n...

manongpengzai的博客 401

【LeetCode】4. Median of Two Sorted Arrays解题报告(Python)

参考博客 测试代码: class Solution: def getKth(self, A, B, k): k = int(k) lenA = len(A); lenB = len(B) if lenA &amp;amp;amp;gt; lenB: return self.getKth(B, A, k) if lenA == 0: r...

L141210113的专栏 1217

【LeetCode】4. Median of Two Sorted Arrays 解题报告(Python)

【LeetCode】4. Median of Two Sorted Arrays 解题报告(Python)题目描述解法:类二分查找 题目地址:https://leetcode.com/problems/median-of-two-sorted-arrays/ 题目描述 There are two sorted arrays nums1 and nums2 of size m and n respe...

ttinch的博客 226

LeetCode 4 — Median of Two Sorted Arrays (C++ Java Python)

题目:http://oj.leetcode.com/problems/median-of-two-sorted-arrays/ There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time comple

龙之梦 6496

【LeetCode】4. Median of Two Sorted Arrays(Python)

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

早知晓的博客 272

LeetCode4. Median of Two Sorted Arrays(C++/Python)

There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assumenums1andn...

qq_41562704的博客 217

Leetcode4答案与解析 - Median of Two Sorted Arrays(python)

原题 Leetcode原题传送门 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may...

liubai01的博客 526

LeetCode【Python3】-p4. Median of Two Sorted Arrays

先耍个流氓 class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1.extend(nums2) nums1.sort() if len(nums1) % 2 == 0: ...

weixin_41666290的博客 205

【python】【leetcode】【算法题目4—Median of Two Sorted Arrays】

一、题目描述 题目原文: There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

一只奋斗的小虫的博客 533

Leetcode 4. Median of Two Sorted Arrays (python+cpp)

题目 解法1:双指针 版本一:time complexity O(m+n),space complexity O(m+n) class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); int p1 = 0, p2 =

qq_37821701的博客 248

【leetcode-Python】- 二分搜索 - 4. Median of Two Sorted Arrays

题目链接 4. Median of Two Sorted Arrays 题目描述 给定两个非降序数组nums1和nums2,大小分别为m和n,返回两个数组合并后的中位数。要求时间复杂度为O(log(m+n)). 示例 输入:nums1 = [1,3],nums2 = [2] 输出:2.00000 输入:nums1 = [1,2],nums2 = [3,4] 输出:2.50000 输入:nums1= [],nums2 = [1] 输出:1.0000 解决思路一 插一句题外话

gulaixiangjuejue的博客 647
上一篇: 3.Longest Substring Without Repeating Characters Leetcode Python
下一篇: 5.Longest Palindromic Substring Leetcode Python
hyperbolechi
博客等级 码龄12年 7粉丝 178原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值