Leetcode代码练习(三)
这一题对于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 }
为了增加代码的可读性,我将注意点通过注释的方式写在了代码里面。