Given two arrays, write a function to compute their intersection.
**Example: **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.
Solution:
public class Solution
{
public int[] intersection(int[] nums1, int[] nums2)
{
Set<Integer> hs = new HashSet<>();
for(int n : nums1)
{
hs.add(n);
}
Set<Integer> resultSet = new HashSet<>();
for(int i : nums2)
{
if(hs.contains(i))
resultSet.add(i);
}
int size = resultSet.size();
int[] result = new int[size];
int i = 0;
Iterator itr = resultSet.iterator();
while(itr.hasNext())
{
result[i++] = (int)itr.next();
}
return result;
}
}