4. Median of Two Sorted Arrays(C++)
来源:互联网 发布:js动态显示时间 编辑:程序博客网 时间:2024/05/18 02:22
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
class Solution {public: double findMedianSortedArrays(const vector<int>& A, const vector<int>& B) { const int m = A.size(); const int n = B.size(); int total = m + n; //0x开头的是十六进制数,total与0x1按位与,效果相当于取total二进制最右边的数字 if (total & 0x1) // if total is odd return find_kth(A.begin(), m, B.begin(), n, total / 2 + 1); else // if total is even return (find_kth(A.begin(), m, B.begin(), n, total / 2) +find_kth(A.begin(), m, B.begin(), n, total / 2 + 1)) / 2.0; }private: static int find_kth(std::vector<int>::const_iterator A, int m, std::vector<int>::const_iterator B, int n, int k) { //always assume that m is equal or smaller than n if (m > n) return find_kth(B, n, A, m, k); if (m == 0) return *(B + k - 1); if (k == 1) return min(*A, *B); //divide k into two parts int ia = min(k / 2, m), ib = k - ia; if (*(A + ia - 1) < *(B + ib - 1)) return find_kth(A + ia, m - ia, B, n, k - ia); else if (*(A + ia - 1) > *(B + ib - 1)) return find_kth(A, m, B + ib, n - ib, k - ib); else return A[ia - 1]; }};
阅读全文
0 0
- 4. Median of Two Sorted Arrays(C++)
- 004Median of Two Sorted Arrays (C)
- leetcode Median of Two Sorted Arrays (C)
- LeetCode 4. Median of Two Sorted Arrays(c++)
- 【leetcode】4. Median of Two Sorted Arrays(Python & C++)
- [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
- 二分图匹配相关算法与题目讲解
- (1)大蚂蚁即时通讯
- tensorflow码源-运行流程
- lib和dll文件的区别和联系
- 客户端配置多个git账号,实现多个服务器免密钥
- 4. Median of Two Sorted Arrays(C++)
- tftp
- Android实现下载进度条图标效果
- asdasdasdasd
- java:数据类型
- nginx for windows
- Sudoku Killer
- R中的Sample函数
- 深入学习 FutureTask