Topic
There is sorted arrays nums1 and nums2 of size m and N respectively. Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).
Solution 1:
Merge two vectors directly, then sort and take the median. Note the processing of odd even numbers of vector lengths after merging. This solution is better thought, but the time complexity is O ((m+n) log (m+n)).
The code is as follows:
Class Solution {public: double findmediansortedarrays (vector<int>& nums1, vector<int>& nums2 ) { vector<int> mergednums; Mergednums.assign (Nums1.begin (), Nums1.end ()); Mergednums.insert (Mergednums.end (), Nums2.begin (), Nums2.end ()); Sort (Mergednums.begin (), Mergednums.end ()); int len1 = Nums1.size (); int len2 = Nums2.size (); Double median = (len1 + len2)%2? mergednums[(len1 + len2) >>1]: (mergednums[(len1 + len2-1) >>1] + mergednums[(len1 + len2) >>1])/2.0;
return median; }};
Solution 2:
Time complexity can reach O (log (m+n)), but the idea is more complex. We can turn this problem into looking for the small number of K, except the k here is the median number.
Reference Explanation:
http://blog.csdn.net/yutianzuijin/article/details/11499917
http://blog.csdn.net/zxzxy1988/article/details/8587244
The code is as follows:
Double findkth (int a[], int m, int b[], int n, int k) {//always assume that M is equal or smaller than n if (M > N) re Turn findkth (b, N, A, M, K); if (M = = 0) return b[k-1]; if (k = = 1) return min (a[0], b[0]); Divide k into the parts int pa = min (k/2, m), PB = K-pa; 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 (int a[], int m, int b[], int n) {int total = m + N; mp 0x1) return findkth (A, M, B, N, TOTAL/2 + 1); else return (Findkth (A, m, B, N, TOTAL/2) + findkth (A, m, B, N, TOTAL/2 + 1))/2; } };
Median of the Sorted arrays--problem-solving notes