Question: Given two arrays, write a function to calculate their intersection.
Example 1:
Input: nums1 = [1,2,2,1],nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the output result must be unique.
We can ignore the order of output results.
Solution 1: Iterate an array
Idea analysis:
Iterate an array and determine whether there is another array
PHP Code implementation:
/** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersection($nums1, $nums2) { $res = []; for($i=0;$i<count($nums1);$i++){ if(in_array($nums1[$i],$nums2)){ $res[] = $nums1[$i]; } } return array_unique($res); }
Usage:
$nums2 = [2,4,6,7,8,99]; $nums1 = [1,2,5,9,9,66,89,90,99,99]; var_dump(intersection($nums1, $nums2));
Complexity analysis:
Time complexity: O(mn)
Solution two: built-in Array function
Idea analysis:
Use array_intersect() function to get the intersection of arrays, and then use array_unique() to remove duplicates
PHP code implementation:
/** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersection($nums1, $nums2) { return array_unique(array_intersect($nums1,$nums2)); }
Usage:
$nums2 = [2,4,6,7,8,99]; $nums1 = [1,2,5,9,9,66,89,90,99,99]; var_dump(intersection($nums1, $nums2));
Solution Three: Violent Solution
Idea Analysis:
First merge the two arrays into one array , then loop through twice to find
PHP code implementation:
/** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersection($nums1, $nums2) { $new_arr = array_merge(array_unique($nums1),array_unique($nums2)); $res = []; for($i=0;$i<count($new_arr);$i++){ for($j=$i+1;$j<count($new_arr);$j++){ if($new_arr[$i] == $new_arr[$j]){ $res[] = $new_arr[$i]; } } } return array_unique($res); }
Usage:
$nums2 = [2,4,6,7,8,99]; $nums1 = [1,2,5,9,9,66,89,90,99,99]; var_dump(intersection($nums1, $nums2));
Complexity analysis:
Time complexity: O(n ^2)
Solution 4: Double pointers
Idea analysis:
First sort the two arrays and push forward through the double pointers to search
PHP code implementation:
/** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersection($nums1, $nums2) { sort($nums1); sort($nums2); $i = $j = 0; $res = []; while($i < count($nums1) && $j < count($nums2)){ if($nums1[$i] == $nums2[$j]){ $res[] = $nums1[$i]; $i++; $j++; }elseif($nums1[$i] < $nums2[$j]){ $i++; }elseif($nums1[$i] > $nums2[$j]){ $j++; } } return array_unique($res); }
Usage:
$nums2 = [2,4,6,7,8,99]; $nums1 = [1,2,5,9,9,66,89,90,99,99]; var_dump(intersection($nums1, $nums2));
Complexity analysis:
Time complexity: O(nlogn)
More PHP related knowledge , please visit php tutorial!
The above is the detailed content of Detailed explanation of three methods to find the intersection of two arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!