LeetCode 4. Median of Two Sorted Arrays
来源:互联网 发布:2k16樱木花道捏脸数据 编辑:程序博客网 时间:2024/06/06 01:52
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
题目要求时间复杂度为
在这一题的Discuss里面看到一种二分查找的方法,时间复杂度是
在Discuss中还看到一种方法,先取中间数,而后找中位数的方法,解释得比较详细,我一开始也是这样想的,觉得太烦了,但是这个方法处理得很好,不过它的时间复杂度应该是
Mark一下,我要多多学习。
class Solution {public: int getkth(int s[], int m, int l[], int n, int k){ if (m > n) return getkth(l, n, s, m, k); if (m == 0) return l[k-1]; if (k == 1) return min(s[0], l[0]); int i = min(m, k/2), j = min(n, k/2); if (s[i-1] > l[j-1]) return getkth(s, m, l + j, n-j, k-j); else return getkth(s+i, m-i, l, n, k-i); return 0; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2){ int m = nums1.size(); int n = nums2.size(); vector<int>::iterator iter; int A[m+1],B[n+1],i; memset(A,0,sizeof(A)); memset(B,0,sizeof(B)); for(i=0,iter=nums1.begin();iter!=nums1.end();i++,iter++){ A[i]=*iter; } for(i=0,iter=nums2.begin();iter!=nums2.end();i++,iter++){ B[i]=*iter; } int l = (m+n+1) >> 1; int r = (m+n+2) >> 1; return (getkth(A, m ,B, n, l) + getkth(A, m, B, n, r)) / 2.0; }};
阅读全文
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
- [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
- [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
- java 反向代理的项目怎么获取访问者IP
- Java编程思想-19枚举类型
- LeetCode-42:Trapping Rain Water
- 4.1.内存这个大话题
- 为Excel单元格后面统一添加一个字符,导Excel数据到数据库
- LeetCode 4. Median of Two Sorted Arrays
- Launcher拖拽框架
- leetcode SQL Employees Earning More Than Their Managers
- 程序员福利——几个不错的技术微信公众号
- MyBatis架包的下载地址和简介地址
- windows7 下nginx1.8.1(稳定版本) 启动、停止和重新加载配置
- 白盒测试方法以及归纳
- 进程通信方式--共享内存(shm)--实现自由通信
- linux系统虚拟鼠标的实现