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)).You may assume nums1 and nums2 cannot be both empty.
(两个已经排序完成的数组nums1和nums2,数组长度分别为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 ind1=0; 
	var ind2=0; 
	var arr=[]; 
	while(ind1<nums1.length && ind2<nums2.length){ 
		if(nums1[ind1]<=nums2[ind2]){
			arr.push(nums1.slice(ind1,ind1+1)[0]);
			ind1++;
		}else{
			arr.push(nums2.slice(ind2,ind2+1)[0]);
			ind2++;
		}
	}
	if(ind1<nums1.length){
        arr = arr.concat(nums1.splice(ind1, nums1.length))
	}
	if(ind2<nums2.length){
        arr = arr.concat(nums2.splice(ind2, nums2.length))
	}
    var pos = arr.length/2
    var res = 0
    if(Number.isInteger(pos)){
        res = (arr[pos-1]+arr[pos])/2
    }else{
        res = arr[Math.floor(pos)]
    }
    return res
};

优化

上面的是比较复杂的一个算法,后来发现,可以在对两个数组进行归并排序的过程中直接检测当前进行排序的数字的index是不是用来求中位数的那一个或者两个数,得到之后就直接跳出while循环。
在这里插入图片描述

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var findMedianSortedArrays = function(nums1, nums2) {
    var ind1=0;
	var ind2=0;
	var sum = 0;
    var res_count = 0
    var pos = (nums1.length+nums2.length-1)/2
    var curindex = -1
	while(ind1<nums1.length || ind2<nums2.length){
        var cur_num = 0
        if(ind1<nums1.length && ind2<nums2.length){
            if(nums1[ind1]<=nums2[ind2]){
                cur_num = nums1[ind1++]
            }else{
                cur_num = nums2[ind2++]
            }
		}else if(ind1>=nums1.length && ind2<nums2.length){
            cur_num = nums2[ind2++]
		}else{
            cur_num = nums1[ind1++]
        }
        curindex++
        if(curindex==Math.ceil(pos)||curindex === Math.floor(pos)){
            sum+=cur_num
            res_count++
        }
        if(curindex > Math.floor(pos)){
            break
        }
	}
    return sum/res_count
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章