Given two arrays, write a function to compute their intersection.
Example:
Givennums1=[1, 2, 2, 1]
,nums2=[2, 2]
, return[2]
.
Note:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) return new int[0];
Set<Integer> set = new HashSet<>();
List<Integer> temp = new ArrayList<>();
for (int num1 : nums1){
set.add(num1);
}
for (int num2 : nums2){
if (set.contains(num2) && !temp.contains(num2)) temp.add(num2);
}
int[] ans = new int[temp.size()];
for (int i = 0; i < temp.size(); i++){
ans[i] = temp.get(i);
}
return ans;
}
}