[leetcode]median of two sorted arrays【寻找第k小的数问题】
来源:互联网 发布:revit 会不会出mac版本 编辑:程序博客网 时间:2024/05/17 08:38
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)).
题意:给两个数组,求出两个数组加起来的中位数。
分析:最简单的方法,定义一个数组,将两个数组合并,然后sort排序,(快排),复杂度为O(nlogn),超时。
还有一种方法,寻找第K小的数。在这个题目中,就是寻找第(m+n)/2个数。
假设k=(m+n)/2,方法是找到nums1中的第k/2-1个数和nums2的第k/2-1个数,比较他们的大小(<,>,=)
如果等于,那么第k小的数就是这两个数之一。
如果小于,那么第k小的数一定在nums2的下一部分。
如果大于,一定在nums1的下一部分。
另外还需要几个边界条件。
如果A或者B为空,则直接返回B[k-1]或者A[k-1];如果k为1,我们只需要返回A[0]和B[0]中的较小值;如果A[k/2-1]=B[k/2-1],返回其中一个;
double findKth(int a[], int m, int b[], int n, int k) { //always assume that m is equal or smaller than n if (m > n) return findKth(b, n, a, m, k); if (m == 0) return b[k - 1]; if (k == 1) return min(a[0], b[0]); //divide k into two parts int pa = min(k / 2, m), pb = k - pa; if (a[pa - 1] < b[pb - 1]) return findKth(a + pa, m - pa, b, n, k - pa); else if (a[pa - 1] > b[pb - 1]) return findKth(a, m, b + pb, n - pb, k - pb); else return a[pa - 1]; } class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int total = m + n; if (total & 0x1) return findKth(A, m, B, n, total / 2 + 1); else return (findKth(A, m, B, n, total / 2) + findKth(A, m, B, n, total / 2 + 1)) / 2; } };
因为每次都有k/2个数被删除,所以时间复杂度为log(k),由于k=(m+n)/2,所以时间复杂度为log(m+n)。
0 0
- [leetcode]median of two sorted arrays【寻找第k小的数问题】
- Leetcode#4.Median of Two Sorted Arrays(归并排序&二分查找求第k小的数)
- leetcode | Median of Two Sorted Arrays 寻找2个有序数组中第k大的值
- LeetCode-4-Median-of-Two-Sorted-Arrays 递归求两有序数组第k小
- Median of Two Sorted Arrays 有序数组A和B合并之后第k小的数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- LeetCode4. Median of Two Sorted Arrays(寻找第k小数:分治O(log(n+m)))
- 【数组&中位数&第K位数】Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays 典型的二分,分治算法, 另 第k小的O(lgk)解法
- [leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- leetcode 第4题 Median of Two Sorted Arrays
- 寻找两个数组的中位数 Median of Two Sorted Arrays ***问题转化思想***
- leetcode题解||Median of Two Sorted Arrays问题
- [c++]LeetCode Median of Two Sorted Arrays问题
- leetcode之Median of Two Sorted Arrays问题
- Median Of Two Sorted Array的寻找k 的解法
- LeetCode: Median of Two Sorted Arrays
- 面向对象思想
- 大学最重要的七项学习
- 坑爹的stl list 的size()成员函数
- 文件预览后续
- wifi 链接流程
- [leetcode]median of two sorted arrays【寻找第k小的数问题】
- java中JVM的原理
- Uva 12169 Disgruntled Judge 扩展欧几里得,暴力
- 理解HTTP幂等性
- APP如何设计才能适配iPhone6/Plus和iPhone5?
- select
- Xamarin.IOS UIAlertController 自定义字体
- Java二维数组长度总结
- 机器学习实战-第2章(k-近邻算法)