Leet Code OJ 4. Median of Two Sorted Arrays [Difficulty: Hard]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lnho2015/article/details/54962206

题目

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

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

翻译

有2个排序过的数组nums1,nums2,它们的长度分别是m和n。
找到两个数组的中位数,总的运行时间需要是 O(log (m+n))。
例1:

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

中位数:2.0

例2:

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

中位数: (2 + 3)/2 = 2.5

分析

以下解法LeetCode时间为65ms,虽然Accepted了,但时间复杂度没到O(log (m+n)),该解法待后续优化。

Java版代码(时间复杂度O(m+n),空间复杂度O(m+n)):

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length == 0 && nums2.length == 0) {
            return 0.0;
        } else if (nums1.length == 0) {
            return getMid(nums2);
        } else if (nums2.length == 0) {
            return getMid(nums1);
        }
        Double mid1 = getMid(nums1), mid2 = getMid(nums2);
        int len = nums1.length + nums2.length;
        int index1 = len / 2, index2 = len / 2;
        if (len % 2 == 0) index1--;
        int sum = 0, current, j = 0, k = 0;
        if (mid1 < mid2) {
            j = nums1.length < 2 ? 0 : nums1.length / 2 - 1;
        } else {
            k = nums2.length < 2 ? 0 : nums2.length / 2 - 1;
        }
        for (int i = j + k; i < len; i++) {
            if (j >= nums1.length) {
                if (sum == 0) {
                    sum = nums2[index1 - nums1.length];
                }
                return (sum + nums2[index2 - nums1.length]) / 2.0;
            } else if (k >= nums2.length) {
                if (sum == 0) {
                    sum = nums1[index1 - nums2.length];
                }
                return (sum + nums1[index2 - nums2.length]) / 2.0;
            }
            if (nums1[j] < nums2[k]) {
                current = nums1[j];
                j++;
            } else {
                current = nums2[k];
                k++;
            }
            if (i == index1) {
                if (index1 == index2) {
                    return current;
                }
                sum = current;
            }
            if (i == index2) {
                sum += current;
                return sum / 2.0;
            }
        }
        return 0;
    }
    public Double getMid(int n[]) {
        int len = n.length;
        if (len == 0) {
            return null;
        }
        if (len % 2 == 0) {
            return (n[len / 2 - 1] + n[len / 2]) / 2.0;
        } else {
            return n[len / 2] / 1.0;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Lnho2015/article/details/54962206