Idea: Set the current available interval at nums1 is [s1,t1), NUMS2:[S2,T2)
1. When an array has a usable interval of 0, because another array is already sequenced, it is directly available
When the minimum or maximum value is to be taken, it is also directly available
2. It is obvious that the total length of the two arrays is an even number when the most intermediate two elements/2.0 are required, the length is odd, only the middle one is required. So you only need to find out the maximum of two elements, this step did not think that can discard the median, directly converted to the K large numbers, resulting in a very ugly first version
3. When it is necessary to take the number of K, set NUMS1[TMP1],NUMS2[TMP2] is the number of K/2 from their respective starting point, then assume NUMS1[TMP1]<NUMS2[TMP2], then obviously [S1,TMP1] This interval is preceded by the number of K, (because [S1,TMP1],[S2,TMP2] is the fraction of the smallest of the respective interval, because Max (NUMS1[S1,TMP1]) <min (NUMS1[TMP1+1,T1), nums2[tmp2,t2 )), so you can remove them directly, and don't forget that the value is also crossed in K.
class Solution{public:const int inf = ~0u >> 1; Vector<int> Nums1,nums2; Double findkthelement (int s1,int t1,int s2,int t2,int k) {//assert (T1-s1 + t2-s2 >= k); if (S1 = = T1) return nums2[s2 + k-1]; else if (s2 = = t2) return nums1[s1 + k-1]; if (k = = 1) return min (Nums1[s1],nums2[s2]); if (k = = t1-s1 + t2-s2) return Max (nums1[t1-1],nums2[t2-1]); int tmp1 = min (S1 + K/2-1,t1-1); int tmp2 = min (s2 + K/2-1,t2-1); if (NUMS1[TMP1] < NUMS2[TMP2]) {return findkthelement (TMP1 + 1,t1,s2,t2,k-tmp1 + s1-1); } else if (NUMS1[TMP1] > NUMS2[TMP2]) {return findkthelement (s1,t1,tmp2 + 1,t2,k-tmp2 + s2- 1); } else {if ((K & 1) = = 0) return NUMS2[TMP2]; else return min ((tmp1 + 1< T1?NUMS1[TMP1 + 1]:inf), (TMP2 + 1< T2?NUMS2[TMP2 + 1]:inf )); }} DouBle findmediansortedarrays (vector<int>& nums1, vector<int>& nums2) {this->nums1 = nums1; THIS->NUMS2 = NUMS2; Sort (Nums1.begin (), Nums1.end ()); Sort (Nums2.begin (), Nums2.end ()); int T1 = nums1.size (), t2 = Nums2.size (); Return ((T1 + t2) & 1) = = 0? (Findkthelement (0,t1,0,t2, (t1 + T2)/2) + findkthelement (0,t1,0,t2, (t1 + T2)/2 + 1))/2.0:findkthelement (0,t1 , 0,t2, (t1 + T2)/2 + 1); }};
Leetcode 4 Median of two Sorted Arrays find median, exclude method difficulty: 1