Leetcode-4 Median of Two Sorted Arrays

题目

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

解析

给出两个已经排序好的数组,求出两个数组合起来的中位数。
题目意思很清晰,条件和结果都很简单,条件是两个已经排序好的数组,结果需要两个数组合起来之后取中位数。

解法1

解法1应该是最常见的一种解法,就是将两个数组头尾相加合并起来,然后重新排序,例如输入 [1,2] [3,4] 两个数组,合并之后变为[1,2,3,4],然后求出中位数。
这种解法很简洁,但是在内存和性能方面的表现非常的差,因为两个已经排列好的数组头尾相加合并之后会变成一个无序的数组,同时占用内存增加了一倍。

解法2

效率更高点的解法应该是利用好两个数组已经排序好的这个特性,通过游标记录移动路径,并记录移动的次数,当移动的次数达到两个数组的中位数时,取得游标附近的值,求得中位数。

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int num1Size = nums1.length , num2Size = nums2.length;
        double result = 0.0;
        int size = num1Size + num2Size;
        int index = 0;
        int num1Index = 0 , num2Index = 0;
        int[] medianArray = new int[2];
        int currentValue = 0;
        while(index <= size/2){
            if(num1Index >= num1Size){
                currentValue = nums2[num2Index++];
            }else if(num2Index >= num2Size){
                currentValue = nums1[num1Index++];
            }
            else if(nums1[num1Index] > nums2[num2Index]){
                currentValue = nums2[num2Index++];
            }
            else{
                currentValue = nums1[num1Index++];
            }
            medianArray[0] = medianArray[1];
            medianArray[1] = currentValue;
            index++;
        }
        // 如果两个数组长度和为偶数,那么中位数有两个,否则只有一个
        if(size%2==0){
            result = (medianArray[0] + medianArray[1]) / 2.0;
        }else{
            result = medianArray[1];
        }
        return result;
    }

猜你喜欢

转载自www.cnblogs.com/benjamin4git/p/10112461.html