zoukankan      html  css  js  c++  java
  • 求两个有序数组的中值

    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 result = [];
        var i=0,j=0,k=0;
        while(i<nums1.length && j<nums2.length){
            if(nums1[i] < nums2[j]){
                result[k++] = nums1[i++];
            }else{
                result[k++] = nums2[j++];
            }
        }
        
        while(i<nums1.length){
            result[k++] = nums1[i++];
        }
        while(j<nums2.length){
             result[k++] = nums2[j++];
        }
        if(result.length %2 !== 0){
            var index = (result.length-1)/2;
            return result[index];
        }else{
            var index = result.length/2;
            return  (result[index]+result[index-1])/2;
        }
        
    };

    问题可以转化为 合并两个有序数组 成为一个新的有序数组

  • 相关阅读:
    完全N叉树寻找祖先
    MySql_Front新建数据库遇到访问地址冲突问题
    C++金额的中文大写
    STL_sort cmp
    螺旋数组
    ~
    Struts向JSP中传值
    Struts1-配置文件部分
    jQuery Ajax 的 load()方式
    jquery animate
  • 原文地址:https://www.cnblogs.com/neverleave/p/5950761.html
Copyright © 2011-2022 走看看