2215. Find the Difference of Two Arrays Easy
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
answer[0]is a list of all distinct integers innums1which are not present innums2.answer[1]is a list of all distinct integers innums2which are not present innums1.
Note that the integers in the lists may be returned in any order.
Example 1:
Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Explanation:
For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].
Example 2:
Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
Output: [[3],[]]
Explanation:
For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
Every integer in nums2 is present in nums1. Therefore, answer[1] = [].
Approach
Input: Two integer arrays nums1, nums2
Output: Find the numbers that do not intersect between the two arrays, return a list answer of length 2
This is a Hash Table problem.
We can use set to remove duplicates from the arrays and store them: s1, s2 = set(nums1), set(nums2).
Separately iterate through these two sets. As long as the iterated value does not appear in the other set, it meets our criteria.
Implementation
from typing import List
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
# Convert the two arrays into sets to remove duplicates and make existence checks fast
s1, s2 = set(nums1), set(nums2)
# Store elements unique to nums1
only1 = []
for n1 in s1:
if n1 not in s2: # If n1 is not in s2, it means it's unique to nums1
only1.append(n1)
# Store elements unique to nums2
only2 = []
for n2 in s2:
if n2 not in s1: # If n2 is not in s1, it means it's unique to nums2
only2.append(n2)
# Return the result in the format: [list of elements unique to nums1, list of elements unique to nums2]
return [only1, only2]/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[][]}
*/
var findDifference = function(nums1, nums2) {
const s1 = new Set(nums1);
const s2 = new Set(nums2);
const only1 = [];
for (let x of s1) {
if (!s2.has(x)) only1.push(x);
}
const only2 = [];
for (let x of s2) {
if (!s1.has(x)) only2.push(x);
}
return [only1, only2];
};Complexity Analysis
- Time Complexity: O(n + m) where n is length of nums1 and m is length of nums2
- Space Complexity: O(n + m) for the two hash sets
Links
2215. Find the Difference of Two Arrays (English)2215. 找出两数组的不同 (Chinese)