4. Median of Two Sorted Arrays
来源:互联网 发布:域名授权系统源码 编辑:程序博客网 时间:2024/05/22 10:44
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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
第一题在leetcode的hard题目,想了很久,因为卡时间复杂度,0(log(m+n)),用什么数据结构都不行,最后想到分别从A和B中不断用2分还是啥的方法才能达到这个时间复杂度。最后也没想出来,参考了别人的思路,不断地2分k(m+n的一半),用归并的思路进行找到第k小的数(此时的k就是中位数)。
int min(int a, int b){ if(a < b) return a; else return b;}double findthemink(int a[], int m, int b[], int n, int k){ if(m > n) return findthemink(b, n, a, m, k); if(m == 0) return b[k - 1]; if(k == 1) return min(a[0], b[0]); int t1, t2; t1 = min(m, k / 2); t2 = k - t1; if(a[t1 - 1] < b[t2 - 1]) return findthemink(a + t1, m - t1, b, n, k - t1); else if(a[t1 - 1] > b[t2 - 1]) return findthemink(a, m, b + t2, n - t2, k - t2); else return a[t1 - 1];}double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int m = nums1Size, n = nums2Size; if((m + n) % 2 == 1) return findthemink(nums1, m, nums2, n, (m + n) / 2 + 1); else return (findthemink(nums1, m, nums2, n, (m + n) / 2) + findthemink(nums1, m, nums2, n, (m + n) / 2 + 1)) / 2;}
0 0
- [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
- 4.Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- leetcoode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- 前端网站收集
- Android退出启动了多个Activity的应用程序
- Kali linux下拓实N95外置网卡驱动安装教程
- 权限管理——用户认证和用户授权
- java 简单版五子棋 递归算法 但是有点小问题 求大神帮助一下
- 4. Median of Two Sorted Arrays
- mysql简单入门三——创建表相关语句
- 【Get深一度】ADS2011.10在win10系统中闪退问题解决方法
- Android-逆向工程
- 关于@synthesize 和 @dynamic 关键字
- 网络信息系统安全检测方案设计(上)
- 第3章 垃圾收集器与内存分配策略
- VS助手安装失败---VS番茄助手安装成功重启VS却没有效果!!!
- Ugly Number II