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

D118 350. Intersection of Two Arrays II

題目連接

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

相關文章
相關標籤/搜索