题意

image.png

解题思路:

  • 满足:l1 < r2 && l2 < r1 表示切割正确

如图所示:

图示:

l1.pngl2.png

PHP 代码实现

  1. class Solution {
  2. function findMedianSortedArrays($nums1, $nums2) {
  3. //选择一个长度最短的来分割,越少的数分割的次数也会越少
  4. if (count($nums1) > count($nums2)) {
  5. return $this->findMedianSortedArrays($nums2, $nums1);
  6. }
  7. if (count($nums1) == 0) {
  8. return floor($nums2[(count($nums2) -1) / 2] + $nums2[count($nums2) / 2]) / 2;
  9. }
  10. $len = count($nums1) + count($nums2);
  11. $cut1 = $cut2 = $cutL = 0;
  12. $cutR = count($nums1);
  13. while ($cut1 <= count($nums1)) {
  14. //满足:l1 < r2 l2 < r1表示切割正确
  15. $cut1 = floor(($cutR - $cutL) / 2) + $cutL;
  16. $cut2 = floor($len / 2) - $cut1;
  17. //cut1 == 0:最左边界
  18. //l1 = $nums1[$cut1 - 1] => [1, 2] => 1
  19. //l2 = $nums2[$cut2 - 1] => [3, 4] => 3
  20. $l1 = ($cut1 == 0) ? PHP_INT_MIN : $nums1[$cut1 - 1];
  21. $l2 = ($cut2 == 0) ? PHP_INT_MIN : $nums2[$cut2 - 1];
  22. $r1 = ($cut1 == count($nums1)) ? PHP_INT_MAX : $nums1[$cut1];
  23. $r2 = ($cut2 == count($nums2)) ? PHP_INT_MAX : $nums2[$cut2];
  24. //保证l1 < r2
  25. if ($l1 > $r2) {
  26. $cutR = $cut1 -1;
  27. } else if ($l2 > $r1) {//说明找的太小,分割往右移动,因为右边值大于左边值
  28. $cutL = $cut1 + 1;
  29. } else {
  30. // 切完之后判断奇偶数
  31. // 如果是偶数
  32. if ($len % 2 == 0) {
  33. $l1 = $l1 > $l2 ? $l1 : $l2;
  34. $r1 = $r1 < $r2 ? $r1 : $r2;
  35. return ($l1 + $r1) / 2;
  36. }
  37. //L: 1,3 R:2 如果是奇数,那就是(r1+r2)/2 = (3+2) / 2 = 2.5
  38. return min($r1, $r2);
  39. }
  40. }
  41. }
  42. function findMedianSortedArrays1($nums1, $nums2) {
  43. $arr = array_merge($nums1, $nums2);
  44. sort($arr);
  45. $num = count($arr);
  46. if ($num % 2) return $arr[$num/2];
  47. //1234 = (2 + 3) / 2
  48. return round(($arr[$num / 2 - 1] + $arr[$num / 2]) / 2, 10);
  49. }
  50. }