4. 寻找两个有序数组的中位数

https://leetcode-cn.com/problems/median-of-two-sorted-arrays/ 

  • 此题的关键是需要确定两个数组的大小,时刻保证左边=右边,数组的奇偶数可以用数学公式去解决。
using System;

public class Problems4
{
public double FindMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.Length, n = nums2.Length; //先保证 后面的数组的长度大于前面的数组 if (m > n) { int[] temp = nums1; nums1 = nums2; nums2 = temp; int tmp = m; m = n; n = tmp; } //halfLen 当m+n为奇数的时候,取值是最中间的那个数,为偶数的时候,取值是偏后面的那个值 int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2; while (iMin <= iMax) { int i = (iMin + iMax) / 2, j = halfLen - i; if (i < iMax && nums2[j - 1] > nums1[i]) { //前面的最大大于后面的最小,需要i向后移动 iMin = i + 1; } else if (i > iMin && nums1[i - 1] > nums2[j]) { iMax = i - 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(nums1[i], nums2[j]); return (maxLeft + minRight) / 2.0; } } return 0.0; } }

 

原文地址:https://www.cnblogs.com/kanekiken/p/10434278.html