码迷,mamicode.com
首页 > 其他好文 > 详细

350. Intersection of Two Arrays II

时间:2018-09-27 13:07:30      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:bsp   -o   java   map   return   ==   tco   def   res   

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

标签:bsp   -o   java   map   return   ==   tco   def   res   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!