zoukankan      html  css  js  c++  java
  • LeetCode解题笔记

    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

    给两个已排序的数组,求中位数。

    //我的解法比较常规,循环,把小的数添加到新数组,直到两个输入数组为空
    /**
     * @param {number[]} nums1
     * @param {number[]} nums2
     * @return {number}
     */
    var findMedianSortedArrays = function(nums1, nums2) {
        var arr=[];
        if(nums2.length===0&&nums1.length0==0)return 0;
        while(nums2.length!==0||nums1.length!==0){
            if(nums1.length === 0){//数组1为空,把目标数组和数组2拼接返回给目标数组
                arr = [].concat(arr,nums2);
                nums2.length = 0;
            }else if (nums2.length === 0) {
                arr = [].concat(arr,nums1);
                nums1.length = 0;
            }else{//判断大小,小的删除元素并添加到目标中
                arr[arr.length] = nums2[0] > nums1[0] ? nums1.shift() : nums2.shift();
            }
        }
        return !(arr.length%2)?(arr[arr.length/2]+arr[arr.length/2-1])/2:arr[Math.floor(arr.length/2)];//返回目标数组的中位数
    };

    这题热门解法写的很多,而且不熟悉其语法,时间关系没有研究。留待以后吧

  • 相关阅读:
    win10上使用linux命令
    leetcode--js--Median of Two Sorted Arrays
    leetcode--js--Longest Substring Without Repeating Characters
    Linux常用的命令
    微信小程序
    leetcode—js—Add Two Numbers
    PHPExcel使用
    console控制台的用法
    git中常混淆的操作
    mysql解析json下的某个字段
  • 原文地址:https://www.cnblogs.com/liyan-web/p/7819330.html
Copyright © 2011-2022 走看看