1. 程式人生 > >350. Intersection of Two Arrays II

350. Intersection of Two Arrays II

() urn keyset key for contains ger leet discus

https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82450/Java-O(m+n)-using-Hash-and-List

 1 class Solution {
 2     public int[] intersect(int[] nums1, int[] nums2) {
 3         if(nums1 == null || nums2 == null) return null;
 4         HashMap<Integer, Integer> map1 = new HashMap<>();
5 HashMap<Integer, Integer> map2 = new HashMap<>(); 6 for(int i = 0; i < nums1.length; i++) { 7 map1.put(nums1[i], map1.getOrDefault(nums1[i], 0)+1); 8 } 9 for(int i = 0; i < nums2.length; i++) { 10 map2.put(nums2[i], map2.getOrDefault(nums2[i], 0)+1);
11 } 12 Set<Integer> set1 = map1.keySet(); 13 Set<Integer> set2 = map2.keySet(); 14 List<Integer> list1 = new ArrayList<>(set1); 15 List<Integer> res = new ArrayList<>(); 16 for(int i = 0; i < list1.size(); i++) {
17 if(set2.contains(list1.get(i))) { 18 for(int j = 0; j < Math.min(map1.get(list1.get(i)), map2.get(list1.get(i))); j++) { 19 res.add(list1.get(i)); 20 } 21 } 22 } 23 int[] res1 = new int[res.size()]; 24 for(int i = 0; i < res.size(); i++) { 25 res1[i] = res.get(i); 26 } 27 return res1; 28 29 } 30 }

350. Intersection of Two Arrays II