Intersection of Two Arrays
给两个数组, 有重复数字, 返回相同的数字的数组, 答案不能有重复元素.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Set<Integer> set1 = new HashSet<>(); for(int n : nums1) { set.add(n); } for(int n : nums2) { if(set.contains(n)) { set1.add(n); } } int[] res = new int[set1.size()]; int k = 0; for(int n : set1) { res[k++] = n; } return res; } } |