[leetcode]349. Intersection of Two Arrays数组交集

时间:2023-03-09 13:01:56
[leetcode]349. Intersection of Two Arrays数组交集

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

题意:

如题

Solution1:  HashSet

1.  Scan nums1,  put items in nums1 to set1

[leetcode]349. Intersection of Two Arrays数组交集

2. Scan nums2, check each item is contained in set1

[leetcode]349. Intersection of Two Arrays数组交集

[leetcode]349. Intersection of Two Arrays数组交集

注意: HashSet.contains() -> O(1)

code

 class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet <Integer> set1 = new HashSet<>();
HashSet <Integer> resSet = new HashSet<>(); for (int i = 0; i < nums1.length; i ++) {
set1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i ++) {
if (set1.contains(nums2[i])) {
resSet.add(nums2[i]);
}
}
// resSet -> int[]res
int [] res = new int[resSet.size()];
int index = 0;
for (int num : resSet) {
res[index++] = num;
}
return res;
}
}