BotByte

Median of Two Sorted Array.cpp

Sep 19th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
  4.         int n = (int) nums1.size();
  5.         int m = (int) nums2.size();
  6.        
  7.         int low = 0, high = n;
  8.         int posINF = INT_MAX, negINF = INT_MIN;
  9.         int median = (n+m)/2 + 1;
  10.         bool odd = ((n+m)%2 == 1);
  11.         double ans;
  12.         while(low <= high){
  13.             int cnt1 = (low+high)/2;
  14.             int cnt2 = median-cnt1;
  15.             if(cnt2 < 0) high = cnt1-1;
  16.             else if(cnt2 > m) low = cnt1+1;
  17.             else {
  18.                 int curNum1 = negINF, curNum2 = negINF;
  19.                 if(cnt1 > 0) curNum1 = nums1[cnt1-1];
  20.                 if(cnt2 > 0) curNum2 = nums2[cnt2-1];
  21.                 int curMaximum = max(curNum1, curNum2);
  22.                
  23.                 int nextNum1 = posINF, nextNum2 = posINF;
  24.                 if(cnt1 < n) nextNum1 = nums1[cnt1];
  25.                 if(cnt2 < m) nextNum2 = nums2[cnt2];
  26.                 int nextMinimum = min(nextNum1, nextNum2);
  27.                 if(curMaximum <= nextMinimum){
  28.                     if(odd) ans = (double) max(curNum1, curNum2);
  29.                     else {
  30.                         int prevNum1 = negINF, prevNum2 = negINF;
  31.                         if(cnt1 > 1) prevNum1 = nums1[cnt1-2];
  32.                         if(cnt2 > 1) prevNum2 = nums2[cnt2-2];
  33.                         int maxs = max(curNum1, curNum2);
  34.                         if(curNum1 == maxs){
  35.                             maxs += max(prevNum1, curNum2);
  36.                         }
  37.                         else {
  38.                             maxs += max(prevNum2, curNum1);
  39.                         }
  40.                         ans = (double) maxs/2.0;
  41.                     }
  42.                     break;
  43.                 }
  44.                 else {
  45.                     if(curNum1 > nextMinimum) high = cnt1-1;
  46.                     else low = cnt1+1;
  47.                 }
  48.             }
  49.         }
  50.         return ans;
  51.     }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment