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

這道題,位于整個題目的,第四題,原本以為是一道水題,就是在做的過程中注意一下邊界條件的處理就可以了的題呢,但是當我看到需要考慮時間復雜度的時候,我瞬間就蒙了,因為時間復雜度要求是log級別的,就是相當于告訴我們,不能把兩個數組直接合并成一個數組了。所以,這題的難度一下子就上來了,后來查了點資料,先把答案曬出來吧,然后再慢慢解釋,為什么要這么做:


public class Solution {
   public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    int total = nums1.length+nums2.length;
    if(total%2==0){
        return (findKth(total/2+1, nums1, nums2, 0, 0)+findKth(total/2, nums1, nums2, 0, 0))/2.0;
    }else{
        return findKth(total/2+1, nums1, nums2, 0, 0);
    }
}
 
public int findKth(int k, int[] nums1, int[] nums2, int s1, int s2){
    if(s1>=nums1.length)
        return nums2[s2+k-1];
 
    if(s2>=nums2.length)
        return nums1[s1+k-1];
 
    if(k==1)
        return Math.min(nums1[s1], nums2[s2]);
 
    int m1 = s1+k/2-1;
    int m2 = s2+k/2-1;
 
    int mid1 = m1<nums1.length?nums1[m1]:Integer.MAX_VALUE;    
    int mid2 = m2<nums2.length?nums2[m2]:Integer.MAX_VALUE;
 
    if(mid1<mid2){
        return findKth(k-k/2, nums1, nums2, m1+1, s2);
    }else{
        return findKth(k-k/2, nums1, nums2, s1, m2+1);
    }
}
}

好了,整個答案就是這個樣子的,其實這個問題,我們是可以把它進行轉換的,我說一下轉換的步驟,大家就應該明白了。

1.找一個數組中最大數和最小數的問題,最笨的方法是,先排序,然后返回最大值,最小值。
2.稍微優化一點的算法就是一個循環下來掃描,采用動態規劃的算法,將最大值,最小值求出來。
3.可以采用建堆的方式,說到這想必大家應該能明白了,就是建立一個大根堆,或者一個小根堆,然后從找找到相應位置的東西即可。
4.我們采用的是第四種,是一個類似于快排的方式,每次我們都隨機將一組數分成兩個部分,然后采用同樣的方法,每次都可以隨機的丟棄數列中的一部分,這樣之后我們就可以舍棄很多數據了。

然后我們這個題,采用的就是大概第四種方法:

Paste_Image.png

思想大概就是上面這種方式,每次都可以舍棄很大的一個部分。然后采用遞歸的方式。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容