codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[1/50] Median of two sorted arrays of different sizes #34

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

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

Dan-Y-Ko commented 5 years ago
const findMedian = (arr1, arr2) => {
  const newArr = [...arr1, ...arr2];
  newArr.sort((a,b) => a-b);

  const mid = Math.floor(newArr.length / 2)
  let median;

  if (newArr.length === 0) return undefined;

  if (newArr.length % 2 === 0) {
    median = (newArr[mid] + newArr[mid-1]) / 2
    return median;
  } else {
    return newArr[mid];
  }
}