004_LeetCode_4 Median of Two Sorted Arrays 题解

来源:互联网 发布:linux的service命令 编辑:程序博客网 时间:2024/06/05 15:36

Description

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

解:

假设nums1的长度小于nums2的长度:

  • inums1划分为两部分nums1_lnums1_r,同时有r=m+n+12nums2划分为两部分nums2_lnums2_r

  • 划分之后,将两个数组对应的左右部分分别对应,如下表:


left right nums1_1 nums1_r nums2_l nums2_r

当满足以下两个条件时:

  • i+j=mi+nj
  • nums2[j1]nums1[i] and nums1[i1]nums2[j]

可以得到中值:


  • m+n为奇数,中值为:max(nums1[i1],nums2[j1])
  • 否则,中值为:max(nums1[i1],nums2[j1])+min(nums1[i],nums2[j])2

Java代码:


class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int m = nums1.length, n = nums2.length;        // 确保n大于m        if (m > n) {            int[] temp = nums1; nums1 = nums2; nums2 = temp;            int tmp = m; m = n; n = tmp;        }        int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2;        while (iMin <= iMax) {            int i = (iMin + iMax) / 2;            int j = halfLen - i;            if (i < iMax && nums2[j-1] > nums1[i]){                // i的值太小                iMin = iMin + 1;            }            else if (i > iMin && nums1[i-1] > nums2[j]) {                // i的值太大                iMax = iMax - 1;            }            else {                int maxLeft = 0;                // 计算左半部分的最大值                if (i == 0) { maxLeft = nums2[j-1]; }                else if (j == 0) { maxLeft = nums1[i-1]; }                else { maxLeft = Math.max(nums1[i-1], nums2[j-1]); }                // 两个数组的长度之和为奇数时,中值为长度的中间值                if ( (m + n) % 2 == 1 ) { return maxLeft; }                // 当两个数组的长度之和为偶数时, 中值等于左半部分的最大值与右半部分的最小值的均值                int minRight = 0;                if (i == m) { minRight = nums2[j]; }                else if (j == n) { minRight = nums1[i]; }                else { minRight = Math.min(nums2[j], nums1[i]); }                return (maxLeft + minRight) / 2.0;            }        }        return 0.0;    }}