Thứ Năm, 12 tháng 12, 2024

[Leetcode] Median of Two Sorted Arrays in JavaScript

 [Leetcode] Median of Two Sorted Arrays in JavaScript

[Leetcode] Median of Two Sorted Arrays in JavaScript



/**
* @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]
};

post written by:

Related Posts

0 nhận xét: