350. Intersection of Two Arrays IIphp
返回给定两个数组的交集。数组
从数量较多的那个数组开始去另外一个数组寻找是否元素存在,个数是否小于等于当前数组。是则填充进交集数组。优化
class Solution { /** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersect($nums1, $nums2) { $a1 = count($nums1); $a2 = count($nums2); $c1 = array_count_values($nums1); $c2 = array_count_values($nums2); $c = $c1; $other = $c2; if($a2>$a1){ $c = $c2; $other = $c1; } $inter = []; foreach($c as $v => $a){ if(isset($other[$v])){ $inter = array_pad($inter, count($inter) + min($a, $other[$v]), $v); } } return $inter; } }
这题只战胜了35%的代码。还有很大的优化空间。.net
若以为本文章对你有用,欢迎用爱发电资助。code