Array Intersection

Medium~15 min

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result should appear as many times as it appears in both arrays. The result can be in any order.

For example, given nums1 = [1, 2, 2, 1] and nums2 = [2, 2], the intersection is [2, 2] because 2 appears twice in both arrays.

Examples

Example 1
Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output: [2, 2]
Explanation: 2 appears twice in nums1 and twice in nums2, so both copies are included.
Example 2
Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
Output: [4, 9]
Explanation: 4 appears once in nums1 and twice in nums2 — take min(1,2)=1. 9 appears once in each — take 1.
Example 3
Input: nums1 = [1, 2, 3], nums2 = [4, 5, 6]
Output: []
Explanation: No elements in common.

Constraints

  • 0 <= nums1.length, nums2.length <= 10^4
  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • Each element in the result appears min(count in nums1, count in nums2) times.
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run