[LeetCode] 349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
Given nums1 =
[1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
Thought process:
Iterate through nums1. Put the elements into a hash set. Iterate through nums2. The elements that the hash set contains are the intersection.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); for (int num : nums1) { set.add(num); } Set<Integer> intersection = new HashSet<>(); for (int num : nums2) { if (set.contains(num)) { intersection.add(num); } } int[] array = new int[intersection.size()]; int i = 0; for (int num : intersection) { array[i] = num; i++; } return array; } } |
Time complexity: O(a + b).
Comments
Post a Comment