LeetCode第4題:尋找兩個有序陣列的中位數

晴&雨發表於2020-07-12

 

 1 double Solution::findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
 2 {
 3     if (nums1.size() > nums2.size())
 4     {
 5         return findMedianSortedArrays(nums2, nums1);
 6     }
 7 
 8     int m = nums1.size();
 9     int n = nums2.size();    //m <= n
10 
11     int left = 0, right = m, ansi=-1;
12     int midNum1 = 0, midNum2 = 0;
13     auto max = [](int a, int b)
14     {
15         return a >= b ? a : b;
16     };
17     auto min = [](int a, int b)
18     {
19         return a <= b ? a : b;
20     };
21     while (left <= right)
22     {
23         int i = (left + right) / 2;
24         int j = (m + n + 1) / 2 - i;
25 
26         int i_1 = i == 0 ? INT_MIN : nums1[i - 1];
27         int i_0 = i == m ? INT_MAX : nums1[i];
28 
29         int j_1 = j == 0 ? INT_MIN : nums2[j - 1];
30         int j_0 = j == n ? INT_MAX : nums2[j];
31         if (i_1 <= j_0)
32         {
33             ansi = i;
34             midNum1 = max(i_1, j_1);
35             midNum2 = min(i_0, j_0);
36             left = i + 1;
37         }
38         else
39         {
40             right = i - 1;
41         }
42     }
43     return (1 == (m + n) % 2) ? (double)midNum1 : (double)(midNum1 + midNum2) / 2;
44 }

 

相關文章