leetcode--js--Median of Two Sorted Arrays
问题描述:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
问题思路:
(1)本题不知道为啥难度级别是hard,但是对于使用js来说,真的挺好做的。可能我没有考虑到什么算法复杂度,还有就是js已经封装好sort算法了。
(2)很自然的想到将nums1 和 nums2 数组组成一个数组,并按序排列,然后找出中值。
(3)js提供扩展运算符或concat,迅速将两个数组组成一个数组;然后使用sort()进行排序
code:
var findMedianSortedArrays = function(nums1, nums2) { var arr = [...nums1, ...nums2].sort((a,b)=>a-b); var a = (nums1.length + nums2.length)%2; var b = (nums1.length + nums2.length)/2; if(a == 0){ return (arr[b-1]+arr[b])/2; }else{ b = Math.floor(b); return arr[b]; } };