Median of two sorted arrays

    0

    0

    pavan koka

    The function finds the median of the arrays nums1 and nums2. It initializes an array called resArr to contain the median values. It compares each value in nums1 and nums2 to see if it is greater than or equal to the median value in resArr. If it is, the value is added to resArr and the index of the value in resArr is incremented. Otherwise, the value in nums2 is added to resArr and the index of the value in resArr is incremented. The function then returns the median of the values in resArr.

    var findMedianSortedArrays = function(nums1, nums2) {
      const resArr = [];
      let i = 0, j = 0;
      while(i < nums1.length || j < nums2.length) {
        if(i === nums1.length) {
          resArr.push(nums2[j])
          j++
          continue
        }
        if(j === nums2.length) {
          resArr.push(nums1[i])
          i++
          continue
        }
        if(nums1[i] < nums2[j]) {
          resArr.push(nums1[i])
          i++
        } else {
          resArr.push(nums2[j])
          j++
        }
      }
      if((resArr.length % 2) === 0) {
        return (
            resArr[parseInt((0+resArr.length-1)/2)] + 
            resArr[(parseInt((0+resArr.length-1)/2)+1)]
          ) / 2
      } else {
        return resArr[(resArr.length-1)/2]
      }
    };
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.