当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Leetcode代码练习(三)

Leetcode代码练习(三)

2018年03月09日  | 移动技术网IT编程  | 我要评论

这一题对于JavaScript来说其实是比较简单的,JavaScript语言对于这一题很多步骤都有现成的API。

 

 

There are two sorted arrays nums1 and nums2 of size m and n respectively.

有两个大小为 m 和 n 的排序数组 nums1 和 nums2 。

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

请找出两个排序数组的中位数并且总的运行时间复杂度为 O(log (m+n)) 。

 

 

例子:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

 

 

这里提一下这里中位数的概念,这里的中位数,是两个数组的中位数,所以要先将两个数组合并排序,然后求出中位数。

中位数要根据数组的长度分别考量,长度为奇数则为中间的那个值,长度为偶数,则为最靠近中间的两个值的平均数。

以下是代码:

 1 var findMedianSortedArrays = function(nums1, nums2) {
 2     //将两个数组拼接成一个数组。
 3     var arr = nums1.concat(nums2);
 4     //将拼接之后的数组,进行排序。
 5     arr = arr.sort(function(a, b) {
 6         return a - b; 
 7     });
 8     var len = arr.length;
 9     //根据数组的长度进行分情况返回,奇数则返回正中间的数,偶数则返回最靠近中间的两个数的平均数。
10     if (len % 2 === 1) {
11         return arr[Math.floor(len/2)];
12     } else {
13         return (arr[len/2 - 1] + arr[len/2]) / 2;
14     }
15 }

为了增加代码的可读性,我将注意点通过注释的方式写在了代码里面。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网