美文网首页
leetcode 4 寻找两个有序数组的中位数

leetcode 4 寻找两个有序数组的中位数

作者: justonemoretry | 来源:发表于2019-10-09 14:00 被阅读0次

题好难,答案都看不懂,太变态了吧

详细解题过程参考了题解,这个题的中心思想是,用i 和j 分别切割数组A和B,切割要实现的目的如下图,就是实现left_part等于right_part,且B[j-1] <=A[i] and A[i-1]<=B[j]。具体实现就是找i的过程。

class Solution {

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {

        int m = nums1.length;

        int n = nums2.length;

        // 交换保证n大于等于m

        if (m > n) {

            int[] temp = nums1;

            nums1 = nums2;

            nums2 = temp;

            int tempNum = m;

            m = n;

            n = tempNum;

        }

        int iMin = 0, iMax = m;

        int halfLength = (m + n + 1) / 2;

        while (iMin <= iMax) {

            int i = (iMin + iMax) / 2;

            int j = halfLength - i;

            if (i < iMax && nums1[i] < nums2[j - 1]) {

                // i偏小

                iMin = i + 1;

            } else if (i > iMin && nums1[i - 1] > nums2[j]) {

                // i偏大

                iMax = i - 1;

            } else {

                // i正常

                int maxLeft = 0;

                if (i == 0) {

                    maxLeft = nums2[j - 1];

                } else if (j == 0) {

                    maxLeft = nums1[i - 1];

                } else {

                    maxLeft = Math.max(nums1[i - 1], nums2[j - 1]);

                }

                if ((m + n) % 2 == 1) {

                        // 总数为奇数时,可以直接返回左侧最大值,因为左侧数目为m+n+1

                        return maxLeft;

                }

                int minRight = 0;

                if (i == m) {

                    minRight = nums2[j];                   

                } else if (j == n) {

                    minRight = nums1[i];

                } else {

                    minRight = Math.min(nums1[i], nums2[j]);

                }

                return (maxLeft + minRight) / 2.0;

            }

        }

        return 0.00;

    }

}

相关文章

网友评论

      本文标题:leetcode 4 寻找两个有序数组的中位数

      本文链接:https://www.haomeiwen.com/subject/wbryyctx.html