leetcode 350. Intersection of Two Arrays II 两个数组的交集

来源:互联网 发布:hbuilder手机版软件 编辑:程序博客网 时间:2024/06/05 09:24

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.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

和上一道题leetcode 349. Intersection of Two Arrays 数组的交集 做法一样,直接使用HashMap来做就可以了,注意这里存在重复的元素。

代码如下:

import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;/* * 使用HashMap要不使用Set高明多了 * */public class Solution {      public int[] intersectByHashMap(int[] nums1, int[] nums2)       {            if(nums1==null || nums1.length<=0 || nums2==null || nums2.length<=0)                return new int[0];            List<Integer> res=new ArrayList<Integer>();            Map<Integer, Integer> map1=new HashMap<>();            for(int i=0;i<nums1.length;i++)                map1.put(nums1[i], map1.getOrDefault(nums1[i], 0)+1);            for(int i=0;i<nums2.length;i++)            {                if(map1.containsKey(nums2[i]) && map1.get(nums2[i])>0)                {                    res.add(nums2[i]);                    map1.put(nums2[i], map1.get(nums2[i])-1);                }            }            int[] res1=new int[res.size()];            for(int i=0;i<res1.length;i++)                res1[i]=res.get(i);            return res1;        }         /*          * 使用排序去做           * */          public int[] intersect(int[] nums1, int[] nums2)           {                if(nums1==null || nums1.length<=0 || nums2==null || nums2.length<=0)                    return new int[0];                List<Integer> res=new ArrayList<Integer>();                Arrays.sort(nums1);                Arrays.sort(nums2);                int i=0,j=0;                while(i<nums1.length && j<nums2.length)                {                    if(nums1[i]==nums2[j])                    {                        res.add(nums1[i]);                        i++;                        j++;                    }else if(nums1[i] > nums2[j])                        j++;                    else                         i++;                }                int[] res1=new int[res.size()];                for(int k=0;k<res1.length;k++)                    res1[k]=res.get(k);                return res1;            }}
阅读全文
0 0
原创粉丝点击