码迷,mamicode.com
首页 > Web开发 > 详细

leetcode--js--Median of Two Sorted Arrays

时间:2018-07-15 12:27:58      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:class   UNC   example   style   lex   使用   运算   组成   log   

 问题描述:

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];
    }  
};

 

leetcode--js--Median of Two Sorted Arrays

标签:class   UNC   example   style   lex   使用   运算   组成   log   

原文地址:https://www.cnblogs.com/hiluna/p/9313166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!