Find the Difference of Two Arrays LeetCode solution in Java

1
class Solution {
2
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
3
Set<Integer> set1 = new HashSet<>(); // create 2 hashsets
4
Set<Integer> set2 = new HashSet<>();
5
for (int num : nums1) {
6
set1.add(num);
7
} // add nums1 elements to set1
8
for (int num : nums2) {
9
set2.add(num);
10
} // add nums2 elements to set2
11

12
List<List<Integer>> resultList =
13
new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return
14
resultList.add(new ArrayList<>());
15
resultList.add(new ArrayList<>());
16

17
for (int num : set1) { // just iterate to all elements of set1
18
if (!set2.contains(num)) {
19
resultList.get(0).add(num);
20
} // add those elements to first sublist of result list, which are not in set2.
21
}
22
for (int num : set2) { // just iterate to all elements of set2
23
if (!set1.contains(num)) {
24
resultList.get(1).add(num);
25
} // add those elements to first sublist of result list, which are not in set1
26
}
27
return resultList;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0