349.md
April 27, 2019 · View on GitHub
:pencil2:Leetcode之PHP版题目解析(349. Intersection of Two Arrays)
2019-04-24 吴亲库里 库里的深夜食堂
:pencil2:描述
从两个数组中找出他们的交集。
:pencil2:题目实例
:pencil2:题目分析
我这里直接把数组元素多的那个进行循环,每次比较元素少的那个数组,只要不同的直接删掉,最后因为交集是要唯一的,所以再去重。可以利用二分查找进行优化。
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @return Integer[]
*/
function intersection($nums1, $nums2) {
$big=count($nums1)>count($nums2)?$nums1:$nums2;
$small=count($nums1)>count($nums2)?$nums2:$nums1;
for($i=0;$i<count($big);$i++){
if(!in_array($small[$i],$big)){
unset($small[$i]);
}
}
return array_unique($small);
}
联系