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.youkuaiyun.com/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
            



BSW: Dcm模块配置--28服务 这个章节讲解下UDS中的28服务(Communcation Control)的配置,顾名思义,对当前ECU的通讯状态进行变更,主要设置应用报文,网络管理报文的收发控制,通常应用在刷写APP软件时,降低总线负载。这里首先要提醒的一点是,28服务几乎不需要手写代码,只有在客户需求要求前置条件不满足时报特定NRC时才需要填充代码。实际配置中主要涉及的模块有DCM,BSWM,ComM,RTE.2.BswM模块的配置。3.ComM模块的配置。1.DCM模块的配置。 阅读详情

相关推荐

黑金AXU9EG开发板深度学习部署全流程解析

本文详细解析了黑金AXU9EG开发板的深度学习模型部署全流程,从环境搭建、模型转换到上板验证,提供了实用的技术指导和优化技巧。该开发板基于Xilinx Zynq UltraScale+ MPSoC架构,特别适合边缘计算场景,通过FPGA加速实现高效AI推理。

weixin_29062613的博客 447

【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的博客 889

从个体到群体:Cartool实战静息态EEG微状态聚类全解析

本文详细解析了使用Cartool软件进行静息态EEG微状态聚类的完整实战流程。从个体水平聚类到群体模板提取,再到指标量化,文章深入探讨了k-means算法的应用、GFP峰值数据的使用技巧以及关键参数设置,为脑电信号处理研究者提供了从数据准备到结果解读的全方位指南。

weixin_29062671的博客 286

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的博客 1543

ic后端学习笔记-floorplan

floorplan是布图规划,规划包括定义芯片的大小,定义芯片内各种模块、hard macros(硬核。比如RAM,ROM及其他IP模块等)、IO等的大小和位置,有时候还需要提前定义一些placement blockages,groups/regions等等,是后端设计的第一步,也是后续所有P&R工作的基础。floorplan与placement的区别是。

tfrofc的博客 5828

毫米波雷达之CFAR 目标检测

恒虚警率(CFAR)算法是一种广泛应用于雷达目标检测的算法,其主要目 标是减少由于杂波与回波之间强度不对称而引起的误报,以确保相对恒定的虚警 率。如图 3.4(a)所示,表示由距离单元组成的一维数据。在待测单元 D 周围选 择若干个背景杂波功率的蓝色单元构成参考滑窗,称为参考单元;而待测单元 D 相邻的若干个不用于背景估计的单元则称为保护单元。当参考单元和保护单元的 维度从一维扩展到二维时,相应的 CFAR 检测由一维 CFAR 演变为二维 CFAR 以处理参考窗口,如图 3.4 (b)所示。

m0_56120826的博客 4920

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

UniApp消息推送进阶:不用插件实现动态语音播报(含保活策略)

本文详细介绍了在UniApp中实现动态语音播报的进阶方案,无需依赖第三方插件。核心采用透传消息传递动态数据,结合本地TTS引擎合成语音,并针对不同安卓厂商提供了深度通道配置与差异化保活策略,有效解决了App退至后台或被清理后语音播报失效的难题。

weixin_29224309的博客 486

[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的博客 932

Java对接(BSC)币安链 | BNB与BEP20的开发实践(三)水龙头 WEB3

这一节我们讲一个币安测试链如何获取到BNB、USDT等BEP20数字货币(水龙头)来让我们前期测试开发。如图:我们将创建的地址填入相应输入框,来获取到测试BNB以及其他BEP20数字币。发币可能需要交易等待,请耐心等待即可,交易完成后,币会到达您的地址内。上一节我们用代码来实现BNB转账、BEP20转账、链上交易监控。2.MetaMask(小狐狸)浏览器插件 🪜。使用EDGE浏览器可以在浏览器直接打开。使用Chrome浏览器,请使用🪜打开。基本工作就绪后,即可进行开发测试。3. 测试区块链浏览器 🪜。

大猩猩的专栏 2790

告别理论!手把手教你用Patran/Nastran搞定机翼颤振分析(附完整模型文件)

本文提供了一份详细的机翼颤振分析实战指南,使用Patran/Nastran软件从零开始构建完整分析模型。涵盖几何建模、网格划分、模态分析到气动弹性耦合的全流程,特别适合航空航天领域工程师学习颤振分析技术。教程包含完整模型文件和实用脚本,帮助读者快速掌握这一关键飞行器设计技能。

weixin_30879169的博客 538

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

快速卷积结构FIR数字滤波器的设计与ARM平台实现

本文提出了一种基于快速卷积结构的FIR数字滤波器设计与实现方案。通过Matlab设计了满足特定指标的低通FIR滤波器,采用重叠-保存法和重叠-相加法两种快速卷积算法,将计算复杂度从O(N·M)降低到O(NlogN)。详细介绍了滤波器系数生成、性能验证流程,并提供了ARM平台C语言实现的关键技术,包括定点量化处理。实验结果表明,该方法能有效滤除混合信号中的高频干扰,保留目标1kHz正弦信号,验证了设计方案的有效性。

huanghm88的专栏 122

LeetCode 4.Median of Two Sorted Arrays (Python)

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

iwanthn的博客 515

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

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

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

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

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

ssm框架搭建

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

【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的专栏 1215

【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的博客 224

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

龙之梦 6495

【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的博客 525

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)).

一只奋斗的小虫的博客 532

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的博客 247
上一篇: 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、付费专栏及课程。

余额充值