首页 > 代码库 > 004. Median of Two Sorted Arrays

004. Median of Two Sorted Arrays

 1 class Solution { 2 public: 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 4         const int m = nums1.size(); 5         const int n = nums2.size(); 6         int total = m + n; 7         if (total & 0x1) return find_kth(nums1.begin(), m, nums2.begin(), n, total / 2 + 1); 8         else  9             return double(find_kth(nums1.begin(), m, nums2.begin(), n, total / 2) + 10                           find_kth(nums1.begin(), m, nums2.begin(), n, total / 2 + 1)) / 2;11     }12 //private:13     int find_kth(vector<int>::const_iterator iter1, int len1, vector<int>::const_iterator iter2, int len2, int count)14     {15         if (len1 > len2) { // 这里比较重要16             return find_kth(iter2, len2, iter1, len1, count);17         }18         else {19             if (len1 == 0) return *(iter2 + count - 1);20             if (count == 1) return min(*iter1, *iter2);21             int m = min(len1, count / 2); // 这里的判定条件22             int n = count - m;23             if (*(iter1 + m - 1) < *(iter2 + n - 1)) return find_kth(iter1 + m, len1 - m, iter2, len2, count - m);24             else if (*(iter1 + m - 1) > *(iter2 + n - 1)) return find_kth(iter1, len1, iter2 + n, len2 - n, count - n);25             else return *(iter1 + m - 1);26         }27     }28 };

 

004. Median of Two Sorted Arrays