• [LeetCode][JavaScript]Median of Two Sorted Arrays


    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)).

    https://leetcode.com/problems/median-of-two-sorted-arrays/


    给定两个排序过的数组,取这两个数组合并后的中位数。

    如果是奇数长度,中位数就是中间的数;如果是偶数长度,中位数是中间两个数的平均数。

    难点是题目要求复杂度是O(m+n)。

    我的解法是先算出两个数组的总长度,然后循环从排序过的两个数组中取比较小的那个,统计长度,当长度等于总长度的一半时,根据奇数和偶数两种情况得到结果。

     1 /**
     2  * @param {number[]} nums1
     3  * @param {number[]} nums2
     4  * @return {number}
     5  */
     6 var findMedianSortedArrays = function(nums1, nums2) {
     7     var i = 0, j = 0, count = 0, middleLeft = -1;
     8     var len = nums1.length + nums2.length;
     9     while(i < nums1.length || j < nums2.length){
    10         var curr = 0;
    11         if(nums2[j] === undefined || nums1[i] <= nums2[j]){
    12             curr = nums1[i];
    13         }else if(nums1[i] === undefined || nums1[i] > nums2[j]){
    14             curr = nums2[j];
    15         }
    16         count++;
    17         if(len % 2 !== 0){
    18             if(count === (len - 1) / 2 + 1){
    19                 return curr;
    20             }
    21         }else{
    22             if(count === len / 2){
    23                 middleLeft = curr;
    24             }else if(count === (len / 2 + 1) && middleLeft !== -1){
    25                 return (curr + middleLeft) / 2;
    26             }
    27         }
    28 
    29         if(nums2[j] === undefined || nums1[i] <= nums2[j]){
    30             i++;
    31         }else if(nums1[i] === undefined || nums1[i] > nums2[j]){
    32             j++;
    33         }
    34     }
    35     return 0;
    36 };
  • 相关阅读:
    package.json和bower的参数解释
    移动端<meta>属性配置讲解(整理)
    PHP Ajax 跨域问题最佳解决方案
    svn客户端的使用
    TotoiseSVN的基本使用方法
    网页设计入门——UCASiGEM前端组寒假培训笔记
    manacher算法笔记
    【luoguP1168】中位数
    【CF848B】 Rooter's Song
    【luoguP1382】楼房
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4592039.html
Copyright © 2020-2023  润新知