首页 > 其他 > 详细

350. Intersection of Two Arrays II

时间:2018-09-27 12:30:34      阅读:164      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/goPanama/p/9712400.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!