1. Find the median of two sorted arrays

Public findMedianSortedArrays(int[] nums1, int[] nums2) {double a = 0, b = 0; public findMedianSortedArrays(int[] nums1, int[] nums2) {double a = 0, b = 0; int size1 = nums1.length; int size2 = nums2.length; int i = 0, j = 0; boolean single = (size1 + size2) % 2 ! = 0; int middle = (size1 + size2) / 2;if (size1 == 0) {
            return single ? nums2[middle] : ((double) nums2[middle] + nums2[middle - 1]) / 2;
        } else if (size2 == 0) {
            return single ? nums1[middle] : ((double) nums1[middle] + nums1[middle - 1]) / 2;
        }

        while (i < size1 && j < size2) {
            if (nums1[i] <= nums2[j]) {
                if (single) {
                    if (i + j == middle) {
                        returnnums1[i]; }}else {
                    if (i + j == middle - 1) {
                        a = nums1[i];
                    } else if (i + j == middle) {
                        b = nums1[i];
                        return (a + b) / 2;
                    }
                }
                i++;
            } else {
                if (single) {
                    if (i + j == middle) {
                        returnnums2[j]; }}else {
                    if (i + j == middle - 1) {
                        a = nums2[j];
                    } else if (i + j == middle) {
                        b = nums2[j];
                        return(a + b) / 2; } } j++; }}if (i == size1) {
            return getMedian(nums1, nums2, size1, single, middle);
        } else if (j == size2) {
            return getMedian(nums2, nums1, size2, single, middle);
        }
        return 0;
    }

    private double getMedian(int[] nums1, int[] nums2, int size1, boolean single, int middle) {
        double b;
        double a;
        if (single) {
            return nums2[middle - size1];
        } else {
            if (middle - size1 > 0) {
                b = nums2[middle - size1];
                a = Math.max(nums2[middle - size1 - 1], nums1[size1 - 1]);
                return (a + b) / 2;
            } else {
                b = nums2[middle - size1];
                a = nums1[size1 - 1];
                return(a + b) / 2; }}}Copy the code