SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* eslint-disable no-var */
  2. /* eslint-disable no-unused-vars */
  3. /*
  4.  * @lc app=leetcode id=4 lang=javascript
  5.  *
  6.  * [4] Median of Two Sorted Arrays
  7.  */
  8. /**
  9.  * @param {number[]} nums1
  10.  * @param {number[]} nums2
  11.  * @return {number}
  12.  */
  13. var findMedianSortedArrays = function (nums1, nums2) {
  14.   if (nums1.length > nums2.length) {
  15.     return findMedianSortedArrays(nums2, nums1);
  16.   }
  17.  
  18.   const xLength = nums1.length;
  19.   const yLength = nums2.length;
  20.  
  21.   let low = 0;
  22.   let high = xLength;
  23.  
  24.   while (low <= high) {
  25.     const xPartition = Math.floor((low + high) / 2);
  26.     const yPartition = Math.floor((xLength + yLength + 1) / 2 - xPartition);
  27.  
  28.     const xMaxLeft = xPartition === 0 ? Number.NEGATIVE_INFINITY : nums1[xPartition - 1];
  29.     const xMinRight = xPartition === xLength ? Number.POSITIVE_INFINITY : nums1[xPartition];
  30.  
  31.     const yMaxLeft = yPartition === 0 ? Number.NEGATIVE_INFINITY : nums2[yPartition - 1];
  32.     const yMinRight = yPartition === yLength ? Number.POSITIVE_INFINITY : nums2[yPartition];
  33.  
  34.     if (xMaxLeft <= yMinRight && yMaxLeft <= xMinRight) {
  35.       if ((xLength + yLength) % 2 === 0) {
  36.         return (Math.max(xMaxLeft, yMaxLeft) + Math.min(yMinRight, xMinRight)) / 2;
  37.       }
  38.       return Math.max(xMaxLeft, yMaxLeft);
  39.     }
  40.     if (xMaxLeft > yMinRight) {
  41.       high = xPartition - 1;
  42.     } else {
  43.       low = xPartition + 1;
  44.     }
  45.   }
  46.  
  47.   return false;
  48. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top