题目描述

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

 

第一次一次AC并击败95%的人……以此留念……

先贴图以证清白:

 

代码:

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int sum = nums1.length +nums2.length;
        int i = 0, j = 0, cnt = 0;
        int [] aux = new int[sum/2+2];
        if(sum % 2 != 0){
            while(cnt != (sum/2 + 1)){
                if(i >= nums1.length) aux[cnt++] = nums2[j++];
                else if (j >= nums2.length ) aux[cnt++] = nums1[i++];
                else if(nums1[i] > nums2[j]) aux[cnt++] = nums2[j++];
                else aux[cnt++] = nums1[i++];
            }
            return aux[cnt-1];
        }
        else {
            while(cnt != (sum/2 + 1)){
                if(i >= nums1.length) aux[cnt++] = nums2[j++];
                else if (j >= nums2.length ) aux[cnt++] = nums1[i++];
                else if(nums1[i] > nums2[j]) aux[cnt++] = nums2[j++];
                else aux[cnt++] = nums1[i++];
            }
            return (aux[cnt-1] + aux[cnt-2])/2.0;
        }
    }
}

 

其实我也不是自己想出来的。。只是看到这题瞬间就想到了归并排序的merge函数。(看来学数据结构和算法真的能提高编程能力!) 于是我翻开了红宝书算法第四版瞅了一眼merge函数……非常非常的简洁。而这题中与merge函数的区别仅仅是两个数组的大小不一样了,只需要定义两个length就可以完美解决。

但其实这样做有一点不足,就是创建了一个新数组,牺牲了空间来换取时间。这也是算法第四版中原地归并思想所提到过的。

附算法第四版merge代码如下:

public class Merge {

    // This class should not be instantiated.
    private Merge() { }

    // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]
    private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
        // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays
        assert isSorted(a, lo, mid);
        assert isSorted(a, mid+1, hi);

        // copy to aux[]
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k]; 
        }

        // merge back to a[]
        int i = lo, j = mid+1;
        for (int k = lo; k <= hi; k++) {
            if      (i > mid)              a[k] = aux[j++];
            else if (j > hi)               a[k] = aux[i++];
            else if (less(aux[j], aux[i])) a[k] = aux[j++];
            else                           a[k] = aux[i++];
        }

        // postcondition: a[lo .. hi] is sorted
        assert isSorted(a, lo, hi);
    }