349. Intersection of Two Arrays

来源:互联网 发布:三菱plc脉冲输出编程 编辑:程序博客网 时间:2024/04/28 00:13

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

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

Note:
Each element in the result must be unique.
The result can be in any order.
Subscribe to see which companies asked this question

解题思路: 给出A/B数组,求出B数组的数字在A数组数字出现的次数。做法是将A数组的数字概率分布放到hashmap中,然后遍历B数组,匹配到有这个数字,则将结果放入到set中,最后将set转化成数组,返回结果。

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        HashSet<Integer> set = new HashSet<Integer>();        for(int i = 0 ; i < nums1.length; ++i)        {            if(map.containsKey(nums1[i]))            {                int value = map.get(nums1[i]);                value++;                map.put(nums1[i], value);            }else            {                map.put(nums1[i], 1);            }        }        for(int i = 0; i < nums2.length; ++i)        {            if(map.containsKey(nums2[i]))            {                set.add(nums2[i]);            }        }       int[] result = new int[set.size()];       int i=0;       for(int n:set)       {           result[i] = n;           i++;       }       return result;    }}
0 0
原创粉丝点击