349. Intersection of Two Arrays 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 进行去重
publicstaticint[] intersection2(int[] nums1, int[] nums2) { Set<Integer> nums1Set = newHashSet<>(); Set<Integer> set = newHashSet<>(); for (int integer : nums1) { nums1Set.add(integer); } for (int integer : nums2) { if (nums1Set.contains(integer)) { set.add(integer); } } int[] result = newint[set.size()]; inti=0; for (int integer : set) { result[i] = integer; i++; } return result; }