1. 程式人生 > 其它 >結對程式設計前程式碼互評

結對程式設計前程式碼互評

連結

給定兩個大小分別為 m 和 n 的正序(從小到大)陣列 nums1 和 nums2。請你找出並返回這兩個正序陣列的 中位數 。

class Solution {

    private int findKth(int[] nums1, int[] nums2, int k) {
        if (nums1.length == 0) {
            return nums2[k - 1];
        }

        if (nums2.length == 0) {
            return nums1[k - 1];
        }

        int[] shorts = nums1.length < nums2.length ? nums1 : nums2;
        int[] longs = shorts == nums1 ? nums2 : nums1;

        if (k <= shorts.length) {
            return findUpMid(shorts, 0, k - 1, longs, 0, k - 1);
        } else if (k <= longs.length) {
            // 0 1 2 3
            // 0 1 [2 3 4 5 [6]] 7 8
            int start2 = k - shorts.length - 1;
            if (longs[start2] >= shorts[shorts.length - 1]) {
                return longs[start2];
            }
            return findUpMid(shorts, 0, shorts.length - 1, longs, start2 + 1, k - 1);
        } else {
            // 0 1 [2 3]
            // 0 1 2 3 4 5 6 [7 8] _ _ [11] _
            int start1 = k - longs.length - 1;
            int start2 = k - shorts.length - 1;

            if (longs[start2] >= shorts[shorts.length - 1]) {
                return longs[start2];
            }

            if (shorts[start1] >= longs[longs.length - 1]) {
                return shorts[start1];
            }

            return findUpMid(shorts, start1 + 1, shorts.length - 1,
                    longs, start2 + 1, longs.length - 1);
        }

    }


    private int findUpMid(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2) {
        while (start1 < end1) {
            int mid1 = (start1 + end1) >> 1;
            int mid2 = (start2 + end2) >> 1;
            int offset = (end1 - start1 + 1) & 1 ^ 1;
            if (nums1[mid1] > nums2[mid2]) {
                end1 = mid1;
                start2 = mid2 + offset;
            } else {
                end2 = mid2;
                start1 = mid1 + offset;
            }
        }

        return Math.min(nums1[start1], nums2[start2]);
    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int total = nums1.length + nums2.length;
        int mid = total / 2;
        if ((total & 1) != 0) {
            return findKth(nums1, nums2, mid + 1);
        } else {
            return (findKth(nums1, nums2, mid) + findKth(nums1, nums2, mid + 1)) / 2.0;
        }
    }
}
心之所向,素履以往 生如逆旅,一葦以航