分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

leetcode--js--Median of Two Sorted Arrays

发布时间:2023-09-06 02:04责任编辑:郭大石关键词:js

 问题描述:

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

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved