350. Intersection of Two Arrays II #123
-
Topics: Given two integer arrays Example 1:
Example 2:
Constraints:
Follow up:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To solve this problem, we can follow these steps: Let's implement this solution in PHP: 350. Intersection of Two Arrays II <?php
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @return Integer[]
*/
function intersect($nums1, $nums2) {
// Count occurrences of each element in both arrays
$counts1 = array_count_values($nums1);
$counts2 = array_count_values($nums2);
$intersection = [];
// Iterate through the first count array
foreach ($counts1 as $num => $count) {
// Check if the element exists in the second array
if (isset($counts2[$num])) {
// Find the minimum occurrence
$minCount = min($count, $counts2[$num]);
// Add the element to the result array, repeated $minCount times
for ($i = 0; $i < $minCount; $i++) {
$intersection[] = $num;
}
}
}
return $intersection;
}
// Example usage:
$nums1 = [1, 2, 2, 1];
$nums2 = [2, 2];
print_r(intersect($nums1, $nums2)); //Output: [2,2]
$nums1 = [4, 9, 5];
$nums2 = [9, 4, 9, 8, 4];
print_r(intersect($nums1, $nums2)); //Output: [4,9]
?> Explanation:
Follow-Up Considerations:
This approach is efficient for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 350. Intersection of Two Arrays II