标签:
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)).
class Solution { private: typedef vector<int>::const_iterator ITE; public: double findkth(ITE l1, ITE r1, ITE l2, ITE r2, int k) { if (r1 - l1 > r2 - l2) return findkth(l2, r2, l1, r1, k); if (l1==r1) return *(l2+k-1); if (k == 1) return min(*l1, *l2); int pa = min(int(r1 - l1), k / 2), pb = k - pa; ITE lpa = l1 + pa - 1, lpb = l2 + pb - 1; if (*lpa < *lpb) return findkth(l1 + pa, r1, l2, r2, pb); else if (*lpa > *lpb) { return findkth(l1, r1, l2 + pb, r2, pa); } else { return *lpa; } } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(), total = m + n; ITE l1 = nums1.begin(), r1 = nums1.end(); ITE l2 = nums2.begin(), r2 = nums2.end(); if (total % 2) return findkth(l1, r1, l2, r2, total / 2 + 1); else { return (findkth(l1, r1, l2, r2, total / 2) + findkth(l1, r1, l2, r2, total / 2 + 1))/2; } } };
Leetcode 04 Median of Two Sorted Arrays
标签:
原文地址:http://www.cnblogs.com/chenwanqq-leetcode/p/4596638.html