Leetcode 之 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.

简单题,不多说了,一个hashmap存nums1的状态, 另一个存储nums2 的, 遍历找到都存在的key值返回

代码:

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int[]insct;
            ArrayListtempList=new ArrayList();
            HashMapmap1=new HashMap(),map2=new HashMap(),map_temp,map_temp2;
            for(int n:nums1){
                if(map1.containsKey(n)){
                    map1.put(n, map1.get(n)+1);
                }
                else
                    map1.put(n,1);
            }
            for(int n:nums2){
                if(map2.containsKey(n)){
                    map2.put(n, map2.get(n)+1);
                }
                else
                    map2.put(n,1);
            }
            if(map1.size()>map2.size()){
                map_temp=map2;
                map_temp2=map1;
            }
            else
            {
                map_temp=map1;
                map_temp2=map2;
            }
            int times;
            for(int n:map_temp.keySet()){
                if(!map_temp2.containsKey(n))continue;
//              System.out.println(map_temp2.containsKey(n)+" "+n);
                times=Math.min(map_temp.get(n),map_temp2.get(n));
                for(int i=0;inew int[tempList.size()];
            for(int i=0;iget(i);
            }
            return insct;
    }
}

你可能感兴趣的:(Leetcode)