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;
    }
}

 

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