题目要求:
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.
思路:通过一个set来记录两个数组中相同的元素,最后把set转为数组
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> hashSet = new HashSet<Integer>();
for(int i=0;i<nums1.length;i++)
{
for(int j=0;j<nums2.length;j++)
{
if(nums1[i]==nums2[j])
{
if(hashSet.contains(nums1[i]))
{
continue;
}else{
hashSet.add(nums1[i]);
}
}
}
}
int[] intersection = new int[hashSet.size()];
int h=0;
Iterator<Integer> it = hashSet.iterator();
while(it.hasNext())
{
intersection[h]=it.next();
h++;
}
return intersection;
}
}