算法-二分查找-寻找两个正序数组的中位数

在这里插入图片描述

我采用的是合并数组的解法

class Solution {
    
    
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    
    
        int len1 = nums1.length;
        int len2 = nums2.length;
        int[] arr = new int[len1 + len2];

        int p1 = 0;
        int p2 = 0;
        int p3 = 0;
        while(p1 < len1 && p2 < len2) {
    
    
            if(nums1[p1] < nums2[p2]) {
    
    
                arr[p3++] = nums1[p1++];
            }else{
    
    
                arr[p3++] = nums2[p2++];
            }
        }
        while(p1 < len1) {
    
    
            arr[p3++] = nums1[p1++];
        }
        while(p2 < len2) {
    
    
            arr[p3++] = nums2[p2++];
        }

        if(arr.length % 2 == 1) {
    
    
            return (double)arr[(arr.length - 1) / 2];
        }else{
    
    
            int t = (arr.length - 1) / 2;
            
            return (double)(arr[t] + arr[t + 1]) / 2;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45100361/article/details/112615034