1. 程式人生 > >Leetcode-4 Median of Two Sorted Arrays

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;
    }