PHP 查找两个有序数组的相同元素
答案
function findArrayCommon($arr1, $arr2)
{
$common = array();
$i = 0;
$j = 0;
$count1 = count($arr1);
$count2 = count($arr2);
while ($i < $count1 && $j < $count2) {
if ($arr1[$i] < $arr2[$j]) {
$i++;
} elseif ($arr1[$i] > $arr2[$j]) {
$j++;
} else {
$common[] = $arr1[$i];
$i++;
$j++;
}
}
return array_values(array_unique($common));
}
答案解析
测试代码:
$arr1 = array(1, 2, 3, 4, 5, 5, 6, 7, 8);
$arr2 = array(1, 3, 3, 5, 5, 5, 6, 6, 9);
$res = findArrayCommon($arr1, $arr2);
// 输出:[1,3,5,6]
print_r(json_encode($res));