欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode | 4. Median of Two Sorted Arrays

程序员文章站 2022-05-14 20:19:39
...

4. Median of Two Sorted Arrays

Description

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)).
You may assume nums1 and nums2 cannot be both empty.

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

Solution: (Java)

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int index1 = 0, index2 = 0, medianIndex, count = 0;
        medianIndex = (nums1.length + nums2.length) / 2;
        int[] arr = new int[medianIndex + 1];
        while (index1 < nums1.length && index2 < nums2.length) {
            if (nums1[index1] <= nums2[index2]) {
                arr[count] = nums1[index1];
                index1++;
            } else {
                arr[count] = nums2[index2];
                index2++;
            }
            count++;
            if (count > medianIndex)
                break;
        }
        if (count <= medianIndex) {
            if (index1 == nums1.length) {
                while (index2 < nums2.length) {
                    arr[count] = nums2[index2];
                    index2++;
                    count++;
                    if (count > medianIndex)
                        break;
                }
            } else {
                while (index1 < nums1.length) {
                    arr[count] = nums1[index1];
                    index1++;
                    count++;
                    if (count > medianIndex)
                        break;
                }
            }
        }
        if ((nums1.length + nums2.length) % 2 == 0)
            return (arr[medianIndex-1] + arr[medianIndex])*1.0 / 2;
        else
            return arr[medianIndex];
    }
}

思路

本题的代码还可以再稍微精简一下,不过这样也比较简单易懂吧,先得到中位数的索引位置,然后从两个数组中,依次把较小的数往新的数组填充,一直到中位数的位置,那么新数组的最后一个或者最后两个数的平均值即为中位数。