4 寻找两个正序数组的中位数(LeetCode HOT 100)

描述:
给定两个大小分别为 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

Soulution:

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int length1 = nums1.length;
        int length2 = nums2.length;
        int i = 0, j = 0;
        int count = 0;
        // 偶数标志
        boolean evenFlag = ((length1 + length2) & 1) != 1;
        // 中位数索引
        int midIndex = (length1 + length2) >> 1;
        // 前一个数
        int pre = 0;
        while (i < length1 || j < length2) {
            int i1 = i < length1 ? nums1[i] : Integer.MAX_VALUE;
            int i2 = j < length2 ? nums2[j] : Integer.MAX_VALUE;
            int curr;
            if (i1 < i2) {
                curr = i1;
                ++i;
            } else {
                curr = i2;
                ++j;
            }

            if (count == midIndex) {
                return evenFlag ? (pre + curr) / 2.0 : curr;
            }
            pre = curr;
            ++count;
        }
        return pre;
    }

Idea:

①使用哨兵简化代码
int i1 = i < length1 ? nums1[i] : Integer.MAX_VALUE;
int i2 = j < length2 ? nums2[j] : Integer.MAX_VALUE;
②位运算提速
boolean evenFlag = ((length1 + length2) & 1) != 1;
int midIndex = (length1 + length2) >> 1;
③元素总数奇数时,中位数index为total/2;偶数时, 中位数index为分别为(total/2)-1,(total/2)

Reslut:

posted @ 2022-03-22 20:58  supermingjun  阅读(24)  评论(0编辑  收藏  举报