Skip to content

Commit 653593f

Browse files
solves #2215: Find the Difference of Two Arrays in java
1 parent 655e0e6 commit 653593f

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,7 @@
721721
| 2200 | [Find All K-Distant Indices in an Array](https://leetcode.com/problems/find-all-k-distant-indices-in-an-array) | [![Java](assets/java.png)](src/FindAllKDistantIndicesInAnArray.java) | |
722722
| 2206 | [Divide Array Into Equal Pairs](https://leetcode.com/problems/divide-array-into-equal-pairs) | [![Java](assets/java.png)](src/DivideArrayIntoEqualPairs.java) | |
723723
| 2210 | [Count Hills and Valleys in an Array](https://leetcode.com/problems/count-hills-and-valleys-in-an-array) | [![Java](assets/java.png)](src/CountHillsAndValleysInAnArray.java) | |
724-
| 2215 | [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays) | | |
724+
| 2215 | [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays) | [![Java](assets/java.png)](src/FindTheDifferenceOfTwoArrays.java) | |
725725
| 2220 | [Minimum Bit Flips to Convert Number](https://leetcode.com/problems/minimum-bit-flips-to-convert-number) | | |
726726
| 2224 | [Minimum Number of Operations to Convert Time](https://leetcode.com/problems/minimum-number-of-operations-to-convert-time) | | |
727727
| 2229 | 🔒 [Check if an array is consecutive](https://leetcode.com/problems/check-if-an-array-is-consecutive) | | |

src/FindTheDifferenceOfTwoArrays.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// https://leetcode.com/problems/find-the-difference-of-two-arrays
2+
// T: O(N + M)
3+
// S: O(N + M)
4+
5+
import java.util.ArrayList;
6+
import java.util.HashSet;
7+
import java.util.List;
8+
import java.util.Set;
9+
10+
public class FindTheDifferenceOfTwoArrays {
11+
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
12+
final Set<Integer> numbers1 = getSetFrom(nums1);
13+
final Set<Integer> numbers2 = getSetFrom(nums2);
14+
final List<Integer> distinctElementsInNums1 = difference(numbers1, numbers2);
15+
final List<Integer> distinctElementsInNums2 = difference(numbers2, numbers1);
16+
17+
return List.of(distinctElementsInNums1, distinctElementsInNums2);
18+
}
19+
20+
private Set<Integer> getSetFrom(int[] array) {
21+
final Set<Integer> set = new HashSet<>();
22+
for (int element : array) {
23+
set.add(element);
24+
}
25+
return set;
26+
}
27+
28+
private List<Integer> difference(Set<Integer> set1, Set<Integer> set2) {
29+
final List<Integer> result = new ArrayList<>();
30+
for (int element : set1) {
31+
if (!set2.contains(element)) result.add(element);
32+
}
33+
return result;
34+
}
35+
}

0 commit comments

Comments
 (0)