Leetcode PHP题解--D118 350. Intersection of Two Arrays II

152 阅读1分钟

D118 350. Intersection of Two Arrays II

题目链接

350. Intersection of Two Arrays II

题目分析

返回给定两个数组的交集。

思路

从数量较多的那个数组开始去另一个数组寻找是否元素存在,个数是否小于等于当前数组。是则填充进交集数组。

最终代码

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%的代码。还有很大的优化空间。

若觉得本文章对你有用,欢迎用爱发电资助。