问题分析:
既然返回值没有重复,我们不妨将结果放进set中,然后对两个set进行比较。
问题求解:
public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < nums1.length; i++) {
set1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
set2.add(nums2[i]);
}
Iterator<Integer> it = set2.iterator();
while (it.hasNext()) {
int num2 = it.next();
if(set1.contains(num2)){
list.add(num2);
}
}
int[] inter = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
inter[i] = list.get(i);
}
return inter;
}
}