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.
这道题我用了2个for,不过其实我发现只要一个也能做,先存进去,然后第二个再放,放不进去就是重复的。
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer> set = new HashSet(); for(int i=0;i<nums1.length;i++){ for(int j=0;j<nums2.length;j++){ if(nums1[i] == nums2[j]){ set.add(nums1[i]); } } } int[] arr = toInt(set); return arr; } public int[] toInt(Set<Integer> set) { int[] a = new int[set.size()]; int i = 0; for (Integer val : set) a[i++] = val; return a; } }