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
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章