leetcode Median of Two Sorted Arrays

来源:互联网 发布:淘宝评价不支持传图 编辑:程序博客网 时间:2024/06/04 01:24

leetcode 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)).
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

思路

这道题目其实比我们想象中的要简单一点,因为当我们看到两个有序数组的时候,自然而然就会往二分搜索或者归并排序上去思考。这到题目的想法就是利用归并排序找到第k个小的数,这个k能根据我们数组的长度算出其中位数。

public double find(int []nums1,int nums2[],int mid) {        int i,j,k;        int []temp = new int[nums1.length + nums2.length];         for (i = 0,j = 0,k = 0;k <= mid;) {            if (i >= nums1.length) {                temp[k++] = nums2[j++];            } else if (j >= nums2.length) {                temp[k++] = nums1[i++];            } else if (nums1[i] < nums2[j]) {                temp[k++] = nums1[i++];            } else {                temp[k++] = nums2[j++];            }        }        return temp[mid];    }    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int m = nums1.length;        int n = nums2.length;        if (((m + n) & 1) == 1) {//如果其是奇数            return find(nums1, nums2, (m + n) >> 1);        } else {            return (find(nums1,nums2,(m + n ) >> 1) +                     find(nums1, nums2, (m + n - 1) >> 1)) / 2;        }    }    public void test1() {        int []nums1 = {1,3};        int []nums2 = {2};        System.out.println("test1的结果:"+findMedianSortedArrays(nums1, nums2));    }    public void test2() {        int []nums1 = {1,2};        int []nums2 = {3,4};        double value = findMedianSortedArrays(nums1, nums2);        System.out.println("test2:"+value);    }    public void test3() {        int []nums1 = {};        int []nums2 = {1};        System.out.println("test3:"+findMedianSortedArrays(nums1, nums2));    }
0 0