[leetcode]Median of Two Sorted Arrays
来源:互联网 发布:js水平时间轴 编辑:程序博客网 时间:2024/06/17 02:48
4. Median of Two Sorted Arrays
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
这题大致有两种解法,第一种使用中位数的定义(将有序数组分为同等两部分)然后通过二分法寻找满足中位数的切割。
第二种解法比较通俗易懂,利用另外一个问题:在两个有序数组中找k-th小的数。
Let’s say we have two arrays:
The array after merging two arrays:
goal: find
Theorem: say if
Assume that
In the merged array, there are
In the first array, there are
In the second array, there are at most
Thus there are at most
How to use this theorem?
Compare
if
else return
So the median of two sorted arrays could be solved in
class Solution {private: int k_th(vector<int>::iterator a, int m, vector<int>::iterator b, int n, int k) { if (m < n) return k_th(b, n, a, m, k); if (n == 0) return *(a + k - 1); if (k == 1) return min(*a, *b); int j = min(k / 2, n); int i = k - j; if (*(a + (i - 1)) > *(b + (j - 1))) return k_th(a, i, b + j, n - j, k - j); return k_th(a + i, m - i, b, j, k - i); }public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); int m1 = k_th(nums1.begin(), m, nums2.begin(), n, (m + n) / 2 + 1); if ((m + n) % 2 == 0) return (m1 + k_th(nums1.begin(), m, nums2.begin(), n, (m + n) / 2)) / 2.0; return m1; }};
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- CodinGame: Temperatures 反思
- Spring的FactoryBean接口理解
- 读扩散和写扩散的理解
- 分布式系统概念与设计——阅读笔记(一)
- Ubuntu 14.04 LTS 搭建wiki服务器
- [leetcode]Median of Two Sorted Arrays
- 【笔记】shiro中的session设置:
- Linux学习进阶路线图
- kali 做的几件事
- MySQL学习笔记
- [学习笔记]Android广播接收器BroadcastReceiver
- APP弱网模拟测试
- 约瑟夫环问题
- Erlang学习系列