题解报告LeetCode#4:寻找两个有序数组的中位数

题意:LeetCode#4:寻找两个有序数组的中位数;他山之玉:liweiwei1419

思路:“使用二分查找找到两个数组的边界线”

中位数:在有两个有序数组的时候,仍然可以把两个数组分割成两个部分。

image-20200921231653645.png

我们使用一条分割线把两个数组分别分割成两部分:

  1. 红线左边和右边的元素个数相等,或者左边元素的个数比右边元素的个数多 1 个;
  2. 红线左边的所有元素的数值 <= 红线右边的所有元素的数值;

那么中位数就一定只与红线两侧的元素有关,确定这条红线的位置使用二分查找。

代码:

  1. public class Solution {
  2. public double findMedianSortedArrays(int[] nums1, int[] nums2) {
  3. // 为了让搜索的范围更小,我们始终让 nums1 是那个更短的数组
  4. if (nums1.length > nums2.length) {
  5. int[] temp = nums1;
  6. nums1 = nums2;
  7. nums2 = temp;
  8. }
  9. int m = nums1.length;
  10. int n = nums2.length;
  11. // 分割线左边的所有元素需要满足的个数 m + (n - m + 1) / 2;
  12. int totalLeft = (m + n + 1) / 2;
  13. // 在 nums1 的区间 [0, m] 里查找恰当的分割线
  14. // 使得 nums1[i - 1] <= nums2[j] && nums2[j - 1] <= nums1[i]
  15. int left = 0;
  16. int right = m;
  17. while (left < right) {
  18. int i = left + (right - left + 1) / 2;
  19. int j = totalLeft - i;
  20. if (nums1[i - 1] > nums2[j]) {
  21. // 下一轮的搜索区间 [left, i - 1]
  22. right = i - 1;
  23. } else {
  24. // 下一轮的搜索区间 [i, right]
  25. left = i;
  26. }
  27. }
  28. int i = left;
  29. int j = totalLeft - i;
  30. int nums1LeftMax = i == 0 ? Integer.MIN_VALUE : nums1[i - 1];
  31. int nums1RightMin = i == m ? Integer.MAX_VALUE : nums1[i];
  32. int nums2LeftMax = j == 0 ? Integer.MIN_VALUE : nums2[j - 1];
  33. int nums2RightMin = j == n ? Integer.MAX_VALUE : nums2[j];
  34. if (((m + n) % 2) == 1) {
  35. return Math.max(nums1LeftMax, nums2LeftMax);
  36. } else {
  37. return (double) ((Math.max(nums1LeftMax, nums2LeftMax)) +
  38. (Math.min(nums1RightMin, nums2RightMin))) / 2;
  39. }
  40. }
  41. }