Median_of_Two_Sorted_Arrays(理论支持和算法总结)
可以将这个题目推广到更naive的情况,找两个排序数组中的第K个最大值(第K个最小值)。
1、直接 merge 两个数组,然后求中位数(第K个最大值或者第K个最小值),能过,不过复杂度是 O(n + m)
python
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
""" tmpresult = []
n1 = 0
n2 = 0 while n1 < len(nums1) or n2 < len(nums2):
if n1 == len(nums1):
tmpresult.append(nums2[n2])
n2 += 1
continue
if n2 == len(nums2):
tmpresult.append(nums1[n1])
n1 += 1
continue
if nums1[n1] < nums2[n2]:
tmpresult.append(nums1[n1])
n1 += 1
else:
tmpresult.append(nums2[n2])
n2 += 1 if (n1+n2)&1 :
return tmpresult[(n1+n2)/2]
else:
return (tmpresult[(n1+n2)/2 - 1] + tmpresult[(n1+n2)/2])/2.0
2、不用直接merge两个数组,借助merge的思想,用两个指针pa和pb访问两个数组,size记录当前的找到了第几个数。时间复杂度O(k), 但是当k 很接近m+n时,这个方法还是O(m+n)。
python
n1 = 0
n2 = 0
left = -1
right = -1
midposition = 0
leftnum = -1
rightnum = -1
if ((len(nums1) + len(nums2)) & 1):
left = right = (len(nums1) + len(nums2))/2
else:
left = (len(nums1) + len(nums2))/2 - 1
right = (len(nums1) + len(nums2))/2 if len(nums1) == 0:
return (nums2[left] + nums2[right])/2.0
if len(nums2) == 0:
return (nums1[left] + nums1[right])/2.0 while n1 < len(nums1) or n2 < len(nums2): if n1 == len(nums1):
if midposition == left:
leftnum = nums2[n2]
if midposition == right:
rightnum = nums2[n2]
midposition += 1
if midposition > right:
break
n2 += 1
continue if n2 == len(nums2):
if midposition == left:
leftnum = nums1[n1]
if midposition == right:
rightnum = nums1[n1]
midposition += 1
if midposition > right:
break
n1 += 1
continue if nums1[n1] <= nums2[n2]: if midposition == left:
leftnum = nums1[n1]
if midposition == right:
rightnum = nums1[n1]
n1 += 1
midposition += 1 else: if midposition == left:
leftnum = nums2[n2]
if midposition == right:
rightnum = nums2[n2]
n2 += 1
midposition += 1 if midposition > right:
break return (leftnum+rightnum)/2.0
3、二分查找的思想
我们可以考虑从k入手。如果我们每次都能够剔除一个一定在第k大元素之前的元素,那么我们需要进行k次。但是如果每次我们都剔除一半呢?所以用这种类似于二分的思想,我们可以这样考虑:
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]
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(object):
def min(self,a,b):
if a>b:
return b
else:
return a def findKthsortedarray(self,nums1,nums2,k):
if len(nums1) > len(nums2):
tmp = nums1
nums1 = nums2
nums2 = tmp
if len(nums1) == 0:
return nums2[k-1]
if k == 1:
return min(nums1[0],nums2[0]) p1 = min(k/2,len(nums1))
p2 = k - p1 if nums1[p1-1] == nums2[p2-1]:
return nums1[p1-1]
if nums1[p1-1] > nums2[p2-1]:
return self.findKthsortedarray(nums1,nums2[p2:],k-p2)
if nums1[p1-1] < nums2[p2-1]:
return self.findKthsortedarray(nums1[p1:],nums2,k-p1) def findMedianSortedArrays(self, nums1, nums2):
num1 = len(nums1)
num2 = len(nums2) if (num1+num2)&1:
return self.findKthsortedarray(nums1,nums2,(num1+num2)/2+1)
else:
return (self.findKthsortedarray(nums1,nums2,(num1+num2)/2) + self.findKthsortedarray(nums1,nums2,(num1+num2)/2+1))/2.0
Median_of_Two_Sorted_Arrays(理论支持和算法总结)的更多相关文章
- hadoop对于压缩文件的支持及算法优缺点
hadoop对于压缩文件的支持及算法优缺点 hadoop对于压缩格式的是透明识别,我们的MapReduce任务的执行是透明的,hadoop能够自动为我们 将压缩的文件解压,而不用我们去关心. 如果 ...
- QCryptographicHash实现哈希值计算,支持多种算法
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:QCryptographicHash实现哈希值计算,支持多种算法 本文地址:http: ...
- 分布式_理论_06_ 一致性算法 Raft
一.前言 五.参考资料 1.分布式理论(六)—— Raft 算法 2.分布式理论(六) - 一致性协议Raft
- 分布式_理论_05_ 一致性算法 Paxos
一.前言 二.参考资料 1.分布式理论(五)—— 一致性算法 Paxos 2.分布式理论(五) - 一致性算法Paxos
- shiro自定义realm支持MD5算法认证(六)
1.1 散列算法 通常需要对密码 进行散列,常用的有md5.sha, 对md5密码,如果知道散列后的值可以通过穷举算法,得到md5密码对应的明文. 建议对md5进行散列时加salt(盐),进行 ...
- day-10 sklearn库实现SVM支持向量算法
学习了SVM分类器的简单原理,并调用sklearn库,对40个线性可分点进行训练,并绘制出图形画界面. 一.问题引入 如下图所示,在x,y坐标轴上,我们绘制3个点A(1,1),B(2,0),C(2,3 ...
- 分布式理论(五)—— 一致性算法 Paxos
前言 Paxos 算法如同我们标题大图:世界上只有一种一致性算法,就是 Paxos.出自一位 google 大神之口. 同时,Paxos 也是出名的晦涩难懂,推理过程极其复杂.楼主在尝试理解 Paxo ...
- 分布式理论(六)—— Raft 算法
前言 我们之前讲述了 Paxos 一致性算法,虽然楼主尝试用最简单的算法来阐述,但仍然还是有点绕.楼主最初怀疑自己太笨,后来才直到,该算法的晦涩难懂不是只有我一个人这么认为,而是国际公认! 所以 Pa ...
- JS国际化网站中英文切换(理论支持所有语言)应用于h5版APP
网页框架类APP实现国际化参考文案一 参考:https://blog.csdn.net/CSDN_LQR/article/details/78026254 另外付有自己实现的方法 本人用于H5版的AP ...
随机推荐
- [洛谷P4345][SHOI2015]超能粒子炮·改
题目大意:给你$n,k$,求:$$\sum\limits_{i=0}^k\binom n i\pmod{2333}$$题解:令$p=2333,f(n,k)\equiv\sum\limits_{i=0} ...
- [Leetcode] gas station 气站
There are N gas stations along a circular route, where the amount of gas at station i isgas[i]. You ...
- Vue语法笔记
Vue.js 的核心是一个允许采用简洁的模板语法来声明式的将数据渲染进 DOM: 事件监听:v-on 指令绑定一个事件监听器 缩写[@] v-on:click 用户输入,绑定数据:v-model ...
- bzoj1057: [ZJOI2007]棋盘制作(悬线法)
题目要求纵横坐标和奇偶性不同的点取值不同,于是我们把纵横坐标和奇偶性为1的点和0的点分别取反,就变成经典的最大全1子矩阵问题了,用悬线法解决. #include<iostream> #in ...
- 软银开放Pepper开发,给机器人写安卓App是怎样一种体验?
日本软银推出的Pepper智能机器人 新浪科技讯 北京时间5月19日下午消息,谷歌Android移动操作系统的触角正在不断扩大,从今天开始,开发者可以为日本电信公司软银的Pepper人形机器人设计An ...
- 2018 BAT最新《前端必考面试题》
2018 BAT最新<前端必考面试题> 1.Doctype作用? 严格模式与混杂模式如何区分?它们有何意义? (1). 声明位于文档中的最前面,处于 标签之前.告知浏览器的解析器,用什么文 ...
- UBOOT启动内核过程
1.摘要 (1).启动4步骤第一步:将内核搬移到DDR中第二步:校验内核格式.CRC等第三步:准备传参第四步:跳转执行内核(2).涉及到的主要函数是:do_bootm和do_bootm_linux(3 ...
- Java中JAVA_HOME与CLASSPATH的解析(转)
很多人在初学Java的时候经常会被书中介绍的一堆环境变量的设置搞得头昏脑胀,很多书中都会在初装JDK的时候让他大家设置JAVA_HOME环境变量,在开发程序的时候设置CLASSPATH环境变量,而很多 ...
- iframe的使用及操作
一.iframe的使用方法: 在一个页面中加入iframe代码,例如: <div class="myiframe"> <iframe src="test ...
- vijos 1037 背包+标记
描述 2001年9月11日,一场突发的灾难将纽约世界贸易中心大厦夷为平地,Mr. F曾亲眼目睹了这次灾难.为了纪念“9?11”事件,Mr. F决定自己用水晶来搭建一座双塔. Mr. F有N块水晶,每块 ...