[Leetcode] Median of Two Sorted Arrays in JavaScript
![]() |
[Leetcode] Median of Two Sorted Arrays in JavaScript |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums1 | |
* @param {number[]} nums2 | |
* @return {number} | |
*/ | |
var findMedianSortedArrays = function(nums1, nums2) { | |
let index1 = 0; | |
let index2 = 0; | |
let array = [] | |
for (let index = 0; index < nums1.length + nums2.length; index++) { | |
let indexValue; | |
if (nums1[index1] === undefined || nums2[index2] === undefined) { | |
if (nums1[index1] === undefined) { | |
indexValue = nums2[index2] | |
index2 += 1; | |
} else if (nums2[index2] === undefined) { | |
indexValue = nums1[index1] | |
index1 += 1; | |
} | |
} else { | |
if (nums1[index1] <= nums2[index2]) { | |
indexValue = nums1[index1] | |
index1 +=1 | |
} else { | |
indexValue = nums2[index2] | |
index2 +=1 | |
} | |
} | |
array.push(indexValue) | |
} | |
const num1 = Math.floor(array.length / 2) - 1; | |
const num2 = num1 + 1; | |
if (array.length % 2 === 0) { | |
return (array[num1] + array[num2])/2 | |
} | |
return array[num2] | |
}; |
0 nhận xét: