# 4.Median of Two Sorted Arrays <span class='tag' data-diff='hard'></span> {%hackmd RN5D4nggQRO8wzNqxuvlNw %} ## 題目 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. **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 ``` ## 思路 ```javascript let temp = nums1.concat(nums2); temp = temp.sort((a,b) => a-b); return temp.length % 2 ? temp[(temp.length-1) /2] : (temp[temp.length/2] + temp[temp.length/2 -1]) /2; ``` 這題其實有點偷吃步,所以只用了3行就把它解決了,主要是透過內建函數`concat`和`sort`將兩個array合併後在排序,然後就可以輕鬆找到中位數了。由於並無法保證內建函數的時間複雜度,所以題目中的$O(log(m+n))$這個條件有可能沒有達成,但code如此簡潔,實在是不想改了XDD 這邊值得一提的是,剛開始提交的時候,結果是Wrong Answer,順了幾次邏輯覺得這樣應該沒有錯,抽絲剝繭下才發現javascript的內建函數在sort時,是轉成字串並用ASCII碼去做比較的!!!所以遇到負數的情況就會出錯!!!必須要用自定義比較函數的才能拿來比較數字。