(Collection)350. Intersection of Two Arrays II

Posted cKK

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(Collection)350. Intersection of Two Arrays II相关的知识,希望对你有一定的参考价值。

/* Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.  */



public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
     Map<Integer,Integer> map=new HashMap();
     List<Integer> list=new ArrayList();
     for(int num : nums1){
         map.put(num,map.getOrDefault(num,0)+1);
     }
     int count=0;
     for(int num : nums2){
         if(map.containsKey(num) && map.get(num)>0){
             list.add(num);
             map.put(num,map.get(num)-1);
         }
     }
     int[] res=new int[list.size()];
     for(int i=0;i<list.size();i++){
         res[i]=list.get(i);
     }
     return res;
    }
}

  

以上是关于(Collection)350. Intersection of Two Arrays II的主要内容,如果未能解决你的问题,请参考以下文章

[MongoDB]MongoDB的ObjectId组成

82576和i350网卡哪个好

Erlang 淘车记 雷克萨斯ES350

海缆探测仪TSS350

海缆探测仪TSS350

海缆探测仪TSS350