4. Median of Two Sorted Arrays

来源:互联网 发布:centos查看php版本 编辑:程序博客网 时间:2024/05/20 22:30

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


Solution:

Tips:

transform it to find the Nth minimum or maximum question in two sorted arrays.


Java Code:

public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int l1 = nums1.length;        int l2 = nums2.length;        if ((l1 + l2) % 2 == 0) {            int left = findTheNthMinimumNumber(nums1, 0, l1 - 1, nums2, 0, l2 - 1, (l1 + l2) / 2);            int right = findTheNthMinimumNumber(nums1, 0, l1 - 1, nums2, 0, l2 - 1, (l1 + l2) / 2 + 1);            return (left + right) / 2.0;        }                return findTheNthMinimumNumber(nums1, 0, l1 - 1, nums2, 0, l2 - 1, (l1 + l2) / 2 + 1);    }        public int findTheNthMinimumNumber(int[] a1, int b1, int e1, int[] a2, int b2, int e2, int k) {        int l1 = e1 - b1 + 1;        int l2 = e2 - b2 + 1;        if (l1 < l2) {            return findTheNthMinimumNumber(a2, b2, e2, a1, b1, e1, k);        }        if (l1 == 0) {            return a2[k - 1];        }        if (l2 == 0) {            return a1[k - 1];        }        if (k == 1) {            return a1[b1] > a2[b2] ? a2[b2] : a1[b1];        }        int i2 = (b2 + k / 2 - 1) > e2 ? e2 : (b2 + k / 2 - 1);        int i1 = b1 + k - (i2 - b2 + 1) - 1;        if (a1[i1] == a2[i2]) {            return a1[i1];        }        if (a1[i1] < a2[i2]) {            return findTheNthMinimumNumber(a1, i1 + 1, e1, a2, b2, i2, i2 - b2 + 1);        }         return findTheNthMinimumNumber(a1, b1, i1, a2, i2 + 1, e2, i1 - b1 + 1);    }}


0 0
原创粉丝点击