leetcode——Median of Two Sorted Arrays
来源:互联网 发布:snmpwalk命令查询端口 编辑:程序博客网 时间:2024/05/16 07:36
题目:
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)).
typedef vector<int>::iterator Iter;//寻找两个数组中的第k大的元素,k从1开始double findKth(const Iter& a, int m, const Iter& 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) //数组a的长度变成0,那么直接从数组b中返回第k大的数 return b[k - 1]; if (k == 1)//k等于1的时候没法分解了 return min(a[0], b[0]); //divide k into two parts //为了防止越界,让pa小于等于m,由于k不一定是偶数,因此让pb = k - pa,只要保证pa + pb = k即可 int pa = min(k / 2, m), pb = k - pa;//pa和pb也是从1开始的 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(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); int total = m + n; if (total & 0x1) return findKth(nums1.begin(), m, nums2.begin(), n, total / 2 + 1); else return (findKth(nums1.begin(), m, nums2.begin(), n, total / 2) + findKth(nums1.begin(), m, nums2.begin(), n, total / 2 + 1)) / 2; }};
0 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
- hdu acm 1016
- wol 远程开机编译源码
- 互联网圈子,黄进磊竟然把它解释的如此霸气!
- windows远程桌面访问ubuntu
- Swift 学习之Using Swift mix and match, network: 写rss阅读器
- leetcode——Median of Two Sorted Arrays
- 数字化高程模型的表达方法
- 使用cppcheck检测代码警告、错误
- 学习笔记(1)-使用regiondata动态加载省市区
- Swift 学习之二十一:?和 !(详解)
- HelloCharts 之饼状图使用
- 1. Android Activity 之间的跳转
- Swift学习这二十二:扩展(extension)
- SharePoint 2010配置图文教程