LeetCode
来源:互联网 发布:贵金属交易软件排行 编辑:程序博客网 时间:2024/06/06 02:25
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
一个递归的思想,时间复杂度O(log(m+n))
每次二分两个数组,当a[i-1] > b[j-1]的时候,说明第k大的数字在a的左边和b的右边;否则,第k大的数字在a的右边b的左边。
就这样递归下去,直到求出值。
class Solution {public: double findMedianSortedArrays(int a[], int m, int b[], int n) { int l = (m + n + 1) >> 1; int r = (m + n + 2) >> 1; return (solve(a, m, b, n, l) + solve(a, m, b, n, r)) / 2.0; } int solve(int a[], int m, int b[], int n, int k) { if (m > n) return solve(b, n, a, m, k); if (m == 0) return b[k-1]; if (k == 1) return min(a[0], b[0]); int i = min(m, k / 2), j = min(n, k / 2); if (a[i - 1] > b[j - 1]) return solve(a, m, b + j, n - j, k - j); else return solve(a + i, m - i, b, n, k - i); }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Javascript 多浏览器兼容性问题及解决方案
- Docker笔记
- Scala构造顺序 提前定义
- Springboot基础篇(二) 简单的增删改查
- HDU 6084 | 2017百度之星资格赛 1005 卡特兰数 + 分块打表
- LeetCode
- TCP协议与UDP协议的区别
- 新路程------imx6的模块编译的Makefile
- Python3.x与Python2.x的区别
- Crossing River
- shell脚本的始末
- Android6.0 Wi-Fi Statemachine
- 【android-architecture】TODO-DataBinding
- poj1704(Nim博弈)Georgia and Bob