LeetCode —— Median of Two Sorted Arrays
来源:互联网 发布:国产pdf编辑软件 编辑:程序博客网 时间:2024/05/29 19:03
链接:http://leetcode.com/onlinejudge#question_4
原题: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)).
思路:取两个数组的中间数比较,然后各自去除相同的长度,这样一来又是原来的问题,仍然找中间的数。
这道题目投机了一下,当数组个数有一个小于6时,我就直接归并了一下,搞定。可以少很多if,else。
代码:
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int aL = 0; int aR = m - 1; int bL = 0; int bR = n - 1; while (true) { int aLen = aR - aL + 1; int bLen = bR - bL + 1; if (aLen <= 5 || bLen <= 5) return getMedian(A, aL, aR, B, bL, bR); int aMid = (aL + aR) / 2; int bMid = (bL + bR) / 2; if (A[aMid] <= B[bMid]) { int minDel = min(aMid - aL - 1, bR - bMid - 1); aL += minDel; bR -= minDel; } else { int minDel = min(bMid - bL - 1, aR - aMid - 1); bL += minDel; aR -= minDel; } } }private: double getMedian(int A[], int aL, int aR, int B[], int bL, int bR) { int i = aL; int j = bL; vector<int> vec; while (i<=aR && j<=bR) { if (A[i] <= B[j]) vec.push_back(A[i++]); else vec.push_back(B[j++]); } while (i<=aR) vec.push_back(A[i++]); while (j<=bR) vec.push_back(B[j++]); if (vec.size() == 0) return 0; if (vec.size() % 2 == 1) return vec[vec.size()/2]; else return (vec[vec.size()/2-1] + vec[vec.size()/2]) / 2.0; }};
- 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——Median of Two Sorted Arrays
- LeetCode题解——4Median of Two Sorted Arrays
- LeetCode——Median of Two Sorted Arrays
- LeetCode OJ——Median of Two Sorted Arrays
- leetcode——Median of Two Sorted Arrays
- LeetCode之路——Median of Two Sorted Arrays
- Leetcode——04Median 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 OJ
- leetcode 4——Median of Two Sorted Arrays
- Leetcode—4.Median of Two Sorted Arrays
- VxWorks 操作系统学习笔记
- OpenCV 3.1.c and 3.1.d 习题解答
- BCMwifi驱动学习
- Oracle游标中直接使用日期变量的问题解决
- 51单片机中怎么将函数或者变量定位到指定地址,非常有用
- LeetCode —— Median of Two Sorted Arrays
- java学习笔记------Java网络编程三
- hdu 2546(01背包)
- 薪水?发展?究竟怎样的工作才算是好工作?
- win8 pro 64 分区安装 正版
- E2题
- hdmi相关
- C语言声明的解析
- SilkTest高级进阶系列1-用textract来识别文本