Leetcode4. 尋找兩個有序數組的中位數

給定兩個大小爲 m 和 n 的有序數組 nums1 和 nums2。

請你找出這兩個有序數組的中位數,並且要求算法的時間複雜度爲 O(log(m + n))。

你可以假設 nums1 和 nums2 不會同時爲空。

示例 1:

nums1 = [1, 3]
nums2 = [2]

則中位數是 2.0
示例 2:

nums1 = [1, 2]
nums2 = [3, 4]

則中位數是 (2 + 3)/2 = 2.5

最簡單的方法:合併成新數組找中間數

實際上我們並不需要合併成新數組也可以找中間數,類似於雙指針,我們要找的是總長度的二分之一,一開始我認爲需要考慮數組的奇偶,以及數組和索引的長短,參考大佬解法後發現並不需要這樣,直接在每次比較中保存相應的值就可以了。

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //鏈表
        int len1 = nums1.length;
        int len2 = nums2.length;
        double res = 0.0;
        int len = len1 + 2;
        int index1 = 0;
        int index2 = 0; 

        if(len /2 != 0){
            for(int i = 0; i < len/2; i++){
                if( i < len11 &&  i < len2){
                    if(nums1[index1] < nums2[index2]){
                         index1++;
                    }else{
                         index2++;
                    }

                }else{
                    if(i < len1){
                        index1++;
                    }else{
                        index2++;
                    }

                }
                
            }
            if()
            res =  (double)Math.min(nums2[index2],nums1[index1]);
        }else{
             for(int i = 0; i < len/2 -1; i++){
                if(nums1[index1] < nums2[index2]){
                    index1++;
                }else{
                    index2++;
                }
                res = (double) (nums2[index2] + nums1[index1])/2;
            }
        }
        return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章