力扣 LeetCode 349. 两个数组的交集(Day3:哈希表)
解题思路:
方法一:数组
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] hash = new int[1001];
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums1.length; i++) hash[nums1[i]] = 1;
for (int i = 0; i < nums2.length; i++)
if (hash[nums2[i]] == 1) set.add(nums2[i]);
int[] res = new int[set.size()];
int cnt = 0;
for (int s : set) res[cnt++] = s;
return res;
}
}
方法二:set
注意使用set.contains判断是否已有该值
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for (int num1 : nums1) set.add(num1);
for (int num2 : nums2)
if (set.contains(num2)) res.add(num2);
int[] ans = new int[res.size()];
int cnt = 0;
for (int x : res)
ans[cnt++] = x;
return ans;
}
}