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;
            ArrayList<Integer>tempList=new ArrayList<Integer>();
            HashMap<Integer,Integer>map1=new HashMap<Integer,Integer>(),map2=new HashMap<Integer,Integer>(),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;i<times;i++)
                    tempList.add(n);
            }
            insct=new int[tempList.size()];
            for(int i=0;i<tempList.size();i++){
                insct[i]=tempList.get(i);
            }
            return insct;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值