Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4. Median of Two Sorted Arrays #178

Open
Tcdian opened this issue May 24, 2020 · 1 comment
Open

4. Median of Two Sorted Arrays #178

Tcdian opened this issue May 24, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 24, 2020

4. Median of Two Sorted Arrays

给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2

请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))

你可以假设 nums1 和 nums2 不会同时为空。

Example 1

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
@Tcdian
Copy link
Owner Author

Tcdian commented May 24, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var findMedianSortedArrays = function(nums1, nums2) {
    if (nums1.length > nums2.length) {
        return findMedianSortedArrays(nums2, nums1);
    }
    const len1 = nums1.length;
    const len2 = nums2.length;
    const half = Math.ceil((len1 + len2) / 2);
    let left = 0;
    let right = len1;
    while(left < right) {
        const i = Math.ceil((left + right) / 2);
        const j = half - i;
        if (nums1[i - 1] > nums2[j]) {
            right = i - 1;
        } else {
            left = i;
        }
    }
    const i = left;
    const j = half - i;
    const nums1LeftMax = i === 0 ? -Infinity : nums1[i - 1];
    const nums2LeftMax = j === 0 ? -Infinity : nums2[j - 1];
    const nums1RightMin = i === len1 ? Infinity : nums1[i];
    const nums2RightMin = j === len2 ? Infinity : nums2[j];
    if ((len1 + len2) % 2 === 1) {
        return Math.max(nums1LeftMax, nums2LeftMax);
    } else {
        return (Math.max(nums1LeftMax, nums2LeftMax) + Math.min(nums1RightMin, nums2RightMin)) / 2;
    }
};

@Tcdian Tcdian added the Classic label May 24, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant