Leetcode PHP solution — d118 350. Intersection of two arrays II

Time:2020-2-16

D118 350. Intersection of Two Arrays II

Title Link

350. Intersection of Two Arrays II

Title Analysis

Returns the intersection of a given array.

thinking

Start from the larger array to find out whether the element exists in another array and whether the number is less than or equal to the current array. If yes, it is filled into the intersection array.

Final code

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;
    }
}

This problem only beat 35% of the code. There is still a lot of room for optimization.

If you think this article is useful to you, you are welcome to use AI power generation support.

Recommended Today

Array of algorithms — sum of three numbers

Sum of three numbers difficultysecondary Here is an array of N integersnums, judgmentnumsAre there three elements a, B, C in a such that a + B + C = 0? Please find all triples that satisfy the condition and do not repeat.be careful:The answer cannot contain duplicate triples. Example:Given array nums = [- 1, 0, […]