median-of-two-sorted-arrays
来源:互联网 发布:怎样在淘宝网卖闲置品 编辑:程序博客网 时间:2024/06/17 00:23
题目描述
There are two sorted arrays A and B 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)).
分析:
两种思路:
1. 直接 merge 两个数组,然后求中位数,能过,不过复杂度是 O(n + m)。
2. 用二分的思路去做,这不好想,还要考虑到奇偶。可以转化思维,去求两个有序数组中的第 K 大数,这样就比较好想了。
代码:
1. Merge
java:
package leetcode.easy.easy;public class FindMedianSortedArrays {/** * @param args */public static void main(String[] args) {int[] A = new int[] {};int[] B = new int[] { 2, 3 };System.out.println(findMedianSortedArrays(A, B));}public static double findMedianSortedArrays(int A[], int B[]) {int lenA = A.length;int lenB = B.length;int[] C = new int[lenA + lenB];int i = 0, j = 0, k = 0;if (lenA != 0 && lenB != 0) {while (i < lenA || j < lenB) {if (i == lenA) {C[k++] = B[j++];continue;}if (j == lenB) {C[k++] = A[i++];continue;}if (A[i] > B[j]) {C[k++] = B[j++];} else {C[k++] = A[i++];}}} else {if (lenA == 0) {while (j < lenB) {C[k++] = B[j++];}}if (lenB == 0) {while (i < lenA) {C[k++] = A[i++];}}}if ((lenA + lenB) % 2 == 1) {return C[(lenA + lenB) / 2];}return (C[(lenA + lenB)/2 - 1] + C[(lenA + lenB)/2]) / 2.0;}}
C++:
class Solution {public:double findMedianSortedArrays(int A[], int m, int B[], int n) {vector<int> C;int pa = 0, pb = 0;// point of A & Bwhile (pa < m || pb < n) {if (pa == m) {C.push_back(B[pb++]);continue;}if (pb == n) {C.push_back(A[pa++]);continue;}if (A[pa] > B[pb])C.push_back(B[pb++]);elseC.push_back(A[pa++]);}if ((n + m)&1)return C[(n+m)/2];elsereturn (C[(n+m)/2 - 1] + C[(n+m)/2]) / 2.0;}};
2. 二分
java:
暂时没看懂,待补充
0 0
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Linux第二弹
- 【Mongodb】morphia与spring结合使用详解
- Android之简易天气预报小应用(xml解析练手)
- 优秀的第三方库
- UVA1034423 out of 5
- median-of-two-sorted-arrays
- jdbc数据库操作
- Opencv中视频播放与进度控制
- 单片机 基础概念
- 82.You are managing an Oracle Database 11g database with the following backup strategy: 1) On Sunday
- hdoj1969Pie
- 栈之括号匹配
- c++primer读书笔记:2.5 类型处理
- 5.6 假设有 5 个学生的姓名和分数采用以下方式存储(相同的数组下标对应一个学生 的姓名和分数): char *name[]={"Smith","John","Mary","Havard","Kai