[LeetCode][2215. Find the Difference of Two Arrays] Java HashSet Solution

By Long Luo

This article is the solution Java HashSet Solution of Problem 2215. Find the Difference of Two Arrays.

Intuition

We can use HashSet\texttt{HashSet} to record the distinct integers of the two arrays and judge whether a distinct integer in nums1\textit{nums}_1 which not present in nums2\textit{nums}_2.

We can only use 22 HashSet\texttt{HashSet}, not 44 HashSet\texttt{HashSet}.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
for (int num : nums2) {
set2.add(num);
set1.remove(num);
}

for (int num : nums1) {
set2.remove(num);
}

List<List<Integer>> ans = new ArrayList<>();
ans.add(new ArrayList<>(set1));
ans.add(new ArrayList<>(set2));
return ans;
}

Analysis

  • Time Complexity: O(m+n)O(m+n).
  • Space Complexity: O(m+n)O(m+n).

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗