博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode--js--Median of Two Sorted Arrays
阅读量:4629 次
发布时间:2019-06-09

本文共 845 字,大约阅读时间需要 2 分钟。

 问题描述:

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

 

转载于:https://www.cnblogs.com/hiluna/p/9313166.html

你可能感兴趣的文章
WinForm 实现验证码
查看>>
[C++]C++中的IO类
查看>>
笔记本电脑(Windows7)实现无线AP
查看>>
JqGridView 1.0.0.0发布
查看>>
欲精一行,必先通十行
查看>>
前端相关html和css
查看>>
celery
查看>>
实现音乐播放器
查看>>
BZOJ1002 [FJOI2007]轮状病毒(最小生成树计数)
查看>>
uv_timer_t的释放问题
查看>>
【bzoj1853】[Scoi2010]幸运数字 容斥原理+搜索
查看>>
【bzoj2770】YY的Treap 权值线段树
查看>>
利用闭包实现多次ajax请求只执行最后一次
查看>>
任务18:控制反转
查看>>
MyEclipse10整合Axis2插件
查看>>
ORACLE触发器详解
查看>>
边工作边刷题:70天一遍leetcode: day 27
查看>>
BZOJ1702: [Usaco2007 Mar]Gold Balanced Lineup 平衡的队列
查看>>
Shell基础命令之echo
查看>>
windows 常用命令
查看>>