Leetcode #4 Median of Two Sorted Arrays
来源:互联网 发布:出国翻译官软件 编辑:程序博客网 时间:2024/06/06 00:04
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小元素的问题。
int findkth(int a[],int m,int b[],int n,int k)
{
if(m>n)
return findkth(b,n,a,m,k);
if(m == 0)
return b[k-1];
if(k==1)
return a[0]<b[0]?a[0]:b[0];
int pa = m<k/2?m:k/2;
int pb = k - pa;
if(a[pa-1] > b[pb-1])
return findkth(a,m,b+pb,n-pb,k-pb);
else if(a[pa-1] < b[pb-1])
return findkth(a+pa,m-pa,b,n,k-pa);
else return a[pa-1];
}
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int total = nums1Size + nums2Size;
if(total%2 == 1)
return findkth(nums1,nums1Size,nums2,nums2Size,total/2+1);
else
return (findkth(nums1,nums1Size,nums2,nums2Size,total/2) + findkth(nums1,nums1Size,nums2,nums2Size,total/2+1))*1.0/2;
}
- Leetcode 4 Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [leetcode 4] Median of Two Sorted Arrays
- LeetCode 4:《Median of Two Sorted Arrays》
- [Leetcode] 4 - Median of Two Sorted Arrays
- leetcode|4|Median of Two Sorted Arrays
- [Leetcode]4Median of Two Sorted Arrays
- leetcode 4 Median of Two Sorted Arrays
- LeetCode #4 Median of Two Sorted Arrays
- LeetCode-4-Median of Two Sorted Arrays
- LeetCode 4 Median of Two Sorted Arrays
- leetcode 4 Median of Two Sorted Arrays
- LeetCode 4 Median of Two Sorted Arrays
- Leetcode[4] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- leetcode 4 -- Median of Two Sorted Arrays
- lockInterruptibly 和lock的区别
- ubuntu连接wifi但是找不到服务器
- Processing实现Google新图标
- 判断用户关闭浏览器-beforeunload事件
- 可视化算法网站
- Leetcode #4 Median of Two Sorted Arrays
- 打算有时间写写博客
- 爬虫学习1
- 设计模式C++实现(4)——饿汉懒汉之单例模式
- 类的实现
- 酷炫的react.js
- struts2 出现com.opensymphony.xwork2.util.ValueStack
- 异常处理最佳实践
- 设计模式C++实现(3)——适配器模式