Intersection of Two Arrays (easy)
Intersection of Two Arrays (easy)
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].Basic Idea:
class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1.length == 0 || nums2.length == 0) return new int[]{}; Arrays.sort(nums1); Arrays.sort(nums2); int i = 0, j = 0; List<Integer> res = new ArrayList<>(); while (i < nums1.length && j < nums2.length) { if (nums1[i] == nums2[j]) { if (res.isEmpty() || res.get(res.size() - 1) != nums1[i]) { res.add(nums1[i]); } i++; j++; } else if (nums1[i] < nums2[j]) { i++; } else { j++; } } return res.stream().mapToInt(Integer::intValue).toArray(); } }
class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1.length == 0 || nums2.length == 0) return new int[0]; Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toCollection(HashSet::new)); List<Integer> list = new ArrayList<>(); for (int num : nums2) { if (set.contains(num)) { list.add(num); set.remove(num); } } return list.stream().mapToInt(Integer::intValue).toArray(); } }