LeetCode解题笔记 - 4. 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)).

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)];//返回目标数组的中位数
};

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

posted @ 2017-11-11 16:26  liyan.web  阅读(145)  评论(0编辑  收藏  举报