Median of Two Sorted Arrays
时间:2024-12-07
浏览:362
作者:佚名
从现在开始,我们要努力学习啦!今天我给大家带来《Median of Two Sorted Arrays》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

给定两个大小分别为 m 和 n 的排序数组 nums1 和 nums2,返回这两个排序数组的中位数。
整体运行时间复杂度应为 o(log (m+n))
example 1: input: nums1 = [1,3], nums2 = [2] output: 2.00000 explanation: merged array = [1,2,3] and median is 2. example 2: input: nums1 = [1,2], nums2 = [3,4] output: 2.50000 explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
限制:
nums1.length == m
nums2.length == n
0 <=米 <=1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
var findMedianSortedArrays = function(nums1, nums2) {
const toltalLength = nums1.length + nums2.length;let x = 0;
let y = 0;
const mergedArr = []
for(let i=0; i< toltalLength;i++){
if(x> nums1.length -1){ nums2.splice(0, y)
mergedArr.push(...nums2)
break; }
if(y> nums2.length -1){
nums1.splice(0, x)
mergedArr.push(...nums1)
break;
}
if(nums1[x] > nums2[y]){
mergedArr.push(nums2[y]);
y++;
continue;
}else{
mergedArr.push(nums1[x]);
x++;
continue;
}
}
if(toltalLength % 2 === 0){
return (mergedArr[toltalLength/2] + mergedArr[toltalLength/2 -1]) /2
}else{
return mergedArr[(toltalLength-1)/2]
}
};
本篇关于《Median of Two Sorted Arrays》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
