Problem:
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)).
You may assume nums1 and nums2 cannot be both empty.
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:
LeetCode官网已经给出了很好的解答,答案是用java和python写的,这里把它改成php形式。基本思路就是二分查找。
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @return Float
*/
function findMedianSortedArrays($nums1, $nums2) {
$m = count($nums1);
$n = count($nums2);
if($m>$n){
$temp = $nums2;
$nums2 = $nums1;
$nums1 = $temp;
$t = $n;
$n = $m;
$m = $t;
}
if($n===0)
throw new Exception("arrays cann't be empty", 1);
$imin = 0;$imax = $m; $half_len = (int)(($m+$n+1)/2);
while($imin<=$imax){
$i = (int)(($imin+$imax)/2);
$j = $half_len - $i;
// echo $i;echo $j;
if ($i < $m and $nums2[$j-1] > $nums1[$i])
# i is too small, must increase it
$imin = $i + 1;
elseif($i > 0 and $nums1[$i-1] > $nums2[$j])
# i is too big, must decrease it
$imax = $i - 1;
else{
if($i==0){
$max_of_left = $nums2[$j-1];
}elseif($j==0){
$max_of_left = $nums1[$i-1];
}else{
$max_of_left = ($nums1[$i-1]>$nums2[$j-1])?$nums1[$i-1]:$nums2[$j-1];
}
if(($m+$n)%2===1)
return $max_of_left;
if($m=$i)
$min_of_right = $nums2[$j];
elseif($j==$n)
$min_of_right = $nums1[$i];
else
$min_of_right = ($nums1[$i]<$nums2[$j])?$nums1[$i]:$nums2[$j];
return ($min_of_right + $max_of_left)/2.0;
}
}
}