当前位置:网站首页>Topic25——4. 寻找两个正序数组的中位数

Topic25——4. 寻找两个正序数组的中位数

2022-06-09 05:38:00 _卷心菜_

题目:给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。

算法的时间复杂度应该为 O(log (m+n)) 。

示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2

示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

提示:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

归并排序思想:
当排到可以计算中位数的数量时停止排序。

class Solution {
    
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    
        int total_len = nums1.length + nums2.length;  //两个数组长度总和
        int mid = total_len / 2;   
        int[] arr = new int[mid + 1];
        int count = 0;
        int i = 0;
        int j = 0;
        while(i < nums1.length && j < nums2.length) {
    
            if(nums1[i] < nums2[j]) {
    
                arr[count] = nums1[i];
                count++;
                i++;
                if(count-1 == mid)
                    break;
            } else {
    
                arr[count] = nums2[j];
                count++;
                j++;
                if(count-1 == mid)
                    break;
            }
        }
        for(int m = i; count <= mid && m < nums1.length; m++) {
    
            arr[count++] = nums1[m];
        }
        for(int n = j; count <= mid && n < nums2.length; n++) {
    
            arr[count++] = nums2[n];
        }
        if(total_len % 2 == 0) {
         //当长度为偶,中位数为mid位置与mid+1的和的一半 当长度为奇,中位数为mid位置的值
            return (arr[mid] + arr[mid - 1]) / 2.0;
        } else {
    
            return arr[mid];
        }
    }
}
原网站

版权声明
本文为[_卷心菜_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Thumb_/article/details/124981104