JavaScript solution O((n + m) /2)


  • 0
    R

    Runtime: 162ms
    Status: Accepted

    var findMedianSortedArrays = function(nums1, nums2) {
      nums1 = nums1 || [];
      nums2 = nums2 || [];
    
      var middleIndex = (nums1.length + nums2.length) / 2;
      var isOddIndex = middleIndex % 1 === 0;
      var indexToCompare = isOddIndex ? middleIndex : Math.floor(middleIndex);
    
      var num1 = 0;
      var num2 = 0;
      var index1 = 0;
      var index2 = 0;
      var activeArray1 = true;
    
      for (var i = 0; i <= indexToCompare; i++) {
        if (nums2.length === index2 || (nums1.length !== (index1) && nums1[index1] <= nums2[index2])) {
          num1 = nums1[index1++];
        } else {
          num1 = nums2[index2++];
        }
    
        if (isOddIndex && i === (indexToCompare - 1)) {
          break;
        }
      }
    
      if (isOddIndex) {
        if (nums2.length === index2 || (nums1.length !== (index1) && nums1[index1] <= nums2[index2])) {
          num2 = nums1[index1];
        } else {
          num2 = nums2[index2];
        }
    
        return (num1 + num2) / 2;
      }
    
      return num1;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.