LeetCode 4 Median of Two Sorted Arrays(二分)
来源:互联网 发布:csol网络连接中断 编辑:程序博客网 时间:2024/04/19 09:36
题意:给出两个升序的序列,长度分别是m和n,求出这两个序列的中位数,要求复杂度不大于O(log(m+n))。
思路:以中位数为界可以将两个序列个分成两个集合,每个序列的第一个集合元素数量之和与第二个集合元素数量之和差的绝对值不超过1.
第一个集合 | 第二个集合
A[0], A[1], ..., A[i-1] | A[i], A[i+1], ..., A[m-1]
B[0], B[1], ..., B[j-1] | B[j], B[j+1], ..., B[n-1]
所以我们二分第一个序列中第一个集合的终点位置,然后就可以计算出第二个序列中第一个集合的中点位置,然后计算是否满足a[i-1]<=b[[j]且b[j-1]<=a[I]即可,这样一来时间复杂度为O(log(min(m,n))).
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); if (m > n) return findMedianSortedArrays(nums2, nums1); int l = 0, r = m, sum = (m+n)>>1, p1, p2, ans1, ans2; if(n & 1) ans1 = ans2 = nums2[n/2]; else ans1 = nums2[n/2-1], ans2 = nums2[(n+2)/2-1]; while (l <= r) { p1 = (l+r) >> 1; p2 = sum - p1; int v1, v2, v3, v4; v1 = p1 == 0 ? -1000000000 : nums1[p1-1]; v2 = p2 == 0 ? -1000000000 : nums2[p2-1]; v3 = p1 == m ? nums2[p2] : nums1[p1]; v4 = p2 == n ? nums1[p1] : nums2[p2]; if (v1 <= v4 && v2 <= v3) { if((n+m) & 1) ans1 = ans2 = min(v3, v4); else ans1 = max(v1, v2), ans2 = min(v3, v4); break; } else if (v1 > v4) r = p1 - 1; else l = p1 + 1; } return (double)(ans1+ans2)/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(二分+思路)
- [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]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
- 【枚举】Vijos P1496 火柴棒等式 【NOIP2008提高组第二题】
- mysql索引失效的几种情况
- [leetcode] p338 Count Bits
- 8.configurable product
- 一个简单的自定义popupwindow
- LeetCode 4 Median of Two Sorted Arrays(二分)
- 1004贪心算法acm
- Ubuntu 使用技巧
- Linux wget命令详解
- Threadpool & C
- ubuntu安装中文字符支持
- 南阳题目96-n-1位数
- Django:视图和URL配置
- Regex(Regular Expression)正则表达式-----持续更新