Description
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
Solution
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { if (0 == (nums1.size() + nums2.size())) { return 0.0; } vector<int> mergeVec; mergeVec.insert(mergeVec.end(), nums1.begin(), nums1.end()); mergeVec.insert(mergeVec.end(), nums2.begin(), nums2.end()); sort(mergeVec.begin(), mergeVec.end()); int mergeVecSize = mergeVec.size(); if (1 == mergeVecSize) { return mergeVec[0]; } if (0 == (mergeVecSize % 2)) { int a = mergeVecSize / 2; int b = a - 1; return (mergeVec[a] + mergeVec[b])/2.0; } else { int a = mergeVecSize / 2; return mergeVec[a]; } } };
网友评论