Median of Two Sorted Arrays

**question:**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
個人思路:尋找兩個有序數組中所有元素的中位數,沒有其他捷徑,只能在對組合後的數組進行排序之後才能找到中位數。所以重心放在這(m+n)個元素的排序上面。唯一區別的是,這是兩個有序序列,所以當任意nums1中的元素Xi大於nums2中的某元素Yj時,則有,對任意m>i,nums1中的元素Xm必定都大於Yj。按照這個思路,只需要記錄下上一次的比較結果,則可以減少比較的次數。

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int temp2=0;  //記錄nums2中的上次插入位置
        ArrayList<Integer> res = new ArrayList<Integer>();
        //將nums1向nums2中插入
        for(int i=0;i<len1;i++){
            for(int j=temp2;j<len2;j++){
                if(nums1[i]<nums2[j]) {
                    res.add(nums1[i]);
                    temp2=j;
                    break;
                }else{
                    res.add(nums2[j]);
                    if(j>=len2-1) {
                        temp2 = len2;
                    }
                }
            }
            if(temp2>=len2){
                res.add(nums1[i]);
            }
        }
        if(temp2<len2){//nums2中還有元素未被插入
            for(int i=temp2;i<len2;i++){
                res.add(nums2[i]);
            }
        }
        if(0==(len1+len2)%2)
            return (res.get((len1+len2)/2-1)+res.get((len1+len2)/2))/2.0;
        else
            return res.get((len1+len2)/2);
    }
發佈了40 篇原創文章 · 獲贊 90 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章