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 ...
随机推荐
- sd卡的访问
一般再访问sd卡前都要获取sd卡的路径,以防止不同的厂商有不同的路径配置.Android提供了Environment类来获取系统当前sd卡路径. Log.d(TAG, Environment.getE ...
- HDOJ(HDU).1284 钱币兑换问题 (DP 完全背包)
HDOJ(HDU).1284 钱币兑换问题 (DP 完全背包) 题意分析 裸的完全背包问题 代码总览 #include <iostream> #include <cstdio> ...
- 爬虫实例——爬取淘女郎相册(通过selenium、PhantomJS、BeautifulSoup爬取)
环境 操作系统:CentOS 6.7 32-bit Python版本:2.6.6 第三方插件 selenium PhantomJS BeautifulSoup 代码 # -*- coding: utf ...
- ACM1598并查集方法
find the most comfortable road Problem Description XX星有许多城市,城市之间通过一种奇怪的高速公路SARS(Super Air Roam Struc ...
- Leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复
1.题目描述 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构. 注意: 允许出现重复元素. insert(val):向集合中插入元素 val. remove(val):当 va ...
- UVA 1213 Sum of Different Primes
https://vjudge.net/problem/UVA-1213 dp[i][j][k] 前i个质数里选j个和为k的方案数 枚举第i个选不选转移 #include<cstdio> # ...
- mysql 多列唯一索引在事务中select for update是不是行锁?
在表中有这么一索引 UNIQUE KEY `customer_id` (`customer_id`,`item_id`,`ref_id`) 问1. 这种多列唯一索引在事务中select for upd ...
- 【uva11987】带删除的并查集
题意:初始有N个集合,分别为 1 ,2 ,3 .....n.有三种操件1 p q 合并元素p和q的集合2 p q 把p元素移到q集合中3 p 输出p元素集合的个数及全部元素的和. 题解: 并查集.只是 ...
- Vuejs - 组件式开发
初识组件 组件(Component)绝对是 Vue 最强大的功能之一.它可以扩展HTML元素,封装可复用代码.从较高层面讲,可以理解组件为自定义的HTML元素,Vue 的编译器为它添加了特殊强大的功能 ...
- bzoj 1084 DP
首先对于m==1的情况非常容易处理(其实这儿因为边界我错了好久...),直接DP就好了,设f[i][k]为这个矩阵前i个选k个矩阵的最大和,那么f[i][k]=max(f[j][k-1]+sum[j+ ...