Advertisement
nikunjsoni

4

May 12th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
  4.         int xLen = nums1.size(), yLen = nums2.size();
  5.         int low=0, high=xLen;
  6.         double ans;
  7.        
  8.         // Corner case when yLen is 0.
  9.         if(yLen == 0){
  10.             int mid = xLen/2;
  11.             if(xLen&1)
  12.                 return double(nums1[mid]);
  13.             else
  14.                 return double(nums1[mid]+nums1[mid-1])/2.0;
  15.         }
  16.        
  17.         while(low <= high){
  18.             int partitionX = (low+high)/2;
  19.             int partitionY = (xLen+yLen+1)/2 - partitionX;
  20.            
  21.             // Handle case where partitionY goes out of bound.
  22.             if(partitionY < 0){
  23.                 high = partitionX-1;
  24.                 continue;
  25.             }
  26.             if(partitionY > yLen){
  27.                 low = partitionX+1;
  28.                 continue;
  29.             }
  30.            
  31.             // Find max element of left sides.
  32.             int maxLeftX = (partitionX == 0) ? INT_MIN : nums1[partitionX-1];
  33.             int maxLeftY = (partitionY == 0) ? INT_MIN : nums2[partitionY-1];
  34.            
  35.             // Find min elements of right sides.
  36.             int minRightX = (partitionX == xLen) ? INT_MAX : nums1[partitionX];
  37.             int minRightY = (partitionY == yLen) ? INT_MAX : nums2[partitionY];
  38.  
  39.             // If conditon is satisfied.
  40.             if(maxLeftX <= minRightY && maxLeftY <= minRightX){
  41.                 if((xLen+yLen)&1)
  42.                     ans = max(maxLeftX, maxLeftY);
  43.                 else
  44.                     ans = double((max(maxLeftX, maxLeftY)+min(minRightX, minRightY))/2.0);
  45.                 break;
  46.             }
  47.             else if(maxLeftX > minRightY){ // Move to left.
  48.                 high = partitionX-1;
  49.             }
  50.             else{  // Move to right.
  51.                 low = partitionX+1;
  52.             }
  53.         }
  54.         return ans;
  55.     }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement