349. Intersection of Two Arrays
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]解题要点:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
int k = 0;
HashSet<Integer> n1 = new HashSet();
for(int i : nums1) n1.add(i);
HashSet<Integer> n2 = new HashSet();
for(int j : nums2) n2.add(j);
if(n1.size() < n2.size()) {
for(int l : n1) {
if(n2.contains(l))
res[k++] = l;
}
}else {
for(int l : n2) {
if(n1.contains(l))
res[k++] = l;
}
}
return Arrays.copyOf(res, k);
}
}Last updated