004. Median of Two Sorted Arrays
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode——004-Median-of-Two-Sorted-Arrays
LeetCode 004 Median of Two Sorted Arrays - Java
[Leetcode] Median of Two Sorted Arrays
LeetCode--median-of-two-sorted-arrays