LeetCode 75
Find the Difference of Two Arrays
- Problem
- LC 2215
- Topic
- Hash Map / Set
- File
- official75_LC2215FindTheDifferenceOfTwoArrays.java
- Path
- pkg5leetcode/official75/official75_LC2215FindTheDifferenceOfTwoArrays.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC2215FindTheDifferenceOfTwoArrays.java
- Approach
- Sets for unique elements in each direction.
- Complexity
- Time O(n+m), Space O(n+m)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Find the Difference of Two Arrays | LC 22155 * APPROACH: Sets for unique elements in each direction.6 * COMPLEXITY: Time O(n+m), Space O(n+m)7 */8import java.util.*;9 10public class official75_LC2215FindTheDifferenceOfTwoArrays {11 static List<List<Integer>> findDifference(int[] nums1, int[] nums2) {12 Set<Integer> s1 = new HashSet<>(), s2 = new HashSet<>();13 for (int n : nums1) s1.add(n);14 for (int n : nums2) s2.add(n);15 List<Integer> a = new ArrayList<>(), b = new ArrayList<>();16 for (int n : s1) if (!s2.contains(n)) a.add(n);17 for (int n : s2) if (!s1.contains(n)) b.add(n);18 return Arrays.asList(a, b);19 }20 21 public static void main(String[] args) {22 List<List<Integer>> r = findDifference(new int[]{1,2,3}, new int[]{2,4,6});23 check(r.get(0).equals(Arrays.asList(1,3)) && r.get(1).equals(Arrays.asList(4,6)), "case1");24 System.out.println("all tests passed");25 }26 27 static void check(boolean cond, String name) {28 if (!cond) throw new AssertionError("FAILED: " + name);29 System.out.println(" PASS " + name);30 }31}