1. 程式人生 > >LeetCode解題筆記 - 4. Median of Two Sorted Arrays

LeetCode解題筆記 - 4. Median of Two Sorted Arrays

res pre cnblogs 返回 熱門 median 輸入 cat find

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)];//返回目標數組的中位數 };

這題熱門解法寫的很多,而且不熟悉其語法,時間關系沒有研究。留待以後吧

LeetCode解題筆記 - 4. Median of Two Sorted Arrays