【leetcode】Median of Two Sorted Arrays
2016-05-04 11:11
387 查看
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)).
思路:
将求解转换为求第k小元素的问题
代码
size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
思路:
将求解转换为求第k小元素的问题
代码
double findKthArrays(int* a1,int m,int* a2,int n,int k) { //m<=n if(m>n)return findKthArrays(a2,n,a1,m,k); if(m==0)return a2[k-1]; if(k==1)return min(a1[0],a2[0]); int pa=min(k/2,m),pb=k-pa; if(a1[pa-1]<a2[pb-1])return findKthArrays(a1+pa,m-pa,a2,n,k-pa); else if(a1[pa-1]>a2[pb-1])return findKthArrays(a1,m,a2+pb,n-pb,k-pb); else return a1[pa-1]; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m=nums1.size(); int n=nums2.size(); int k=m+n; if(k&1) { return findKthArrays(&nums1[0],m,&nums2[0],n,(k+1)/2); }else { return ((double)findKthArrays(&nums1[0],m,&nums2[0],n,k/2)+(double)findKthArrays(&nums1[0],m,&nums2[0],n,k/2+1))/2.0; } }
相关文章推荐
- Eclipse 导入外部项目无法识别为web项目并且无法在部署到tomcat下
- shell中$0,$?,$!等的特殊用法
- 【codevs1935】【BZOJ2879】美食节,网络流之动态加点
- 圆形头像带描边的工具类
- Windows自动更新API (5)
- poj1125——Stockbroker Grapevine(floyd算法)
- csdn博客好渣啊 用了2次就放弃不想用了
- 【Python】批量创建线程
- 五种开源协议的比较(BSD,Apache,GPL,LGPL,MIT) – 整理
- 白话设计——浅谈DIP和IOC
- PLSQL插入数据中文乱码的问题
- 苹果Xcode帮助文档阅读指南
- [Angularjs]常见api函数
- 纯css 写三角形
- PreferenceActivity的使用
- Windows自动更新API (4)
- boost多线程编程条件变量
- 毕业设计之带有ajax的function()函数返回值问题
- MPVolumeSettingsAlertShow
- Windows自动更新API (3)