Description:
Given two arrays, write a function to compute their intersection.
Solution:
用HashSet
import java.util.*;
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<Integer>();
HashSet<Integer> set2 = new HashSet<Integer>();
for (int i = 0; i < nums1.length; i++)
set.add(nums1[i]);
for (int i = 0; i < nums2.length; i++)
if (set.contains(nums2[i]))
set2.add(nums2[i]);
int arr[] = new int[set2.size()];
int index = 0;
for (Iterator<Integer> it = set2.iterator(); it.hasNext();) {
int val = it.next();
arr[index++] = val;
}
return arr;
}
}