Open songyy5517 opened 6 months ago
Approach: HashSet
Complexity Analysis
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
// Intuition: HashMap
// 1. Exception handling
if (nums1 == null || nums2 == null)
return new ArrayList();
// 2. Define variables
HashSet<Integer> hs1 = new HashSet();
HashSet<Integer> hs2 = new HashSet();
for (int i : nums1)
hs1.add(i);
for (int i : nums2)
hs2.add(i);
for (int i : nums1)
hs2.remove(i);
for (int i : nums2)
hs1.remove(i);
return List.of(List.copyOf(hs1), List.copyOf(hs2));
}
}
2024/5/16
hs.remove(num)
: remove elements from hashset;List.copyOf
: generate List from Collection;List.of
: generate a List with specific elments.
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
Note that the integers in the lists may be returned in any order.
Example 1:
Example 2:
Intuition This problem is to find the exclusive elements in each array. A simple idea is to use two hashsets to store the elements of two arrays respectively. Then for each hashset, we remove the elements appearing in the other array (not hashset). Finally, we combine these two hashsets into a List and return the list.