Skip to content

4. Median of Two Sorted Arrays

https://leetcode.com/problems/median-of-two-sorted-arrays/

js
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var findMedianSortedArrays = function(nums1, nums2) {
  var m = nums1.length
  var n = nums2.length
  var mid = (m + n) / 2
  var i = 0
  var j = 0
  var prev = 0
  var next = 0

  while ((i + j) <= mid) {
    prev = next
    if (i >= m) {
      next = nums2[j++]
    } else if (j >= n) {
      next = nums1[i++]
    } else if (nums1[i] < nums2[j]) {
      next = nums1[i++]
    } else {
      next = nums2[j++]
    }
  }

  return (m + n) % 2 === 0 ? (prev + next) / 2 : next
}
py
class Solution(object):

    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        m, n = len(nums1), len(nums2)
        mid = (m + n) / 2.0
        i, j = 0, 0
        prev, nxt = 0, 0

        while (i + j) <= mid:
            prev = nxt
            if i >= m:
                nxt = nums2[j]
                j += 1
            elif j >= n:
                nxt = nums1[i]
                i += 1
            elif nums1[i] < nums2[j]:
                nxt = nums1[i]
                i += 1
            else:
                nxt = nums2[j]
                j += 1

        return (prev + nxt) / 2.0 if (m + n) % 2 == 0 else nxt
go
package main

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
	m, n := len(nums1), len(nums2)
	mid := (m + n) / 2
	i, j := 0, 0
	prev, next := 0, 0

	for i+j <= mid {
		prev = next

		if i >= m {
			next = nums2[j]
			j++
		} else if j >= n {
			next = nums1[i]
			i++
		} else if nums1[i] < nums2[j] {
			next = nums1[i]
			i++
		} else {
			next = nums2[j]
			j++
		}
	}

	if (m+n)%2 == 0 {
		return float64(prev+next) / 2
	} else {
		return float64(next)
	}
}