关闭

Leetcode no. 350

97人阅读 评论(0) 收藏 举报
分类:

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.

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 num2'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?

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map= new HashMap<>();
        List<Integer> list= new LinkedList<>();
        for (int ele: nums1) {
            if (map.containsKey(ele)) map.put(ele, map.get(ele)+1);
            else map.put(ele, 1);
        }
        for (int ele: nums2) {
            if (map.containsKey(ele) && map.get(ele)>0){
                list.add(ele);
                map.put(ele, map.get(ele)-1);
            }
        }
        int[] res= new int[list.size()];
        int i=0;
        Iterator it= list.iterator();
        while (it.hasNext()){
            res[i++]=(Integer) it.next();
        }
        return res;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12101次
    • 积分:1169
    • 等级:
    • 排名:千里之外
    • 原创:111篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条
    文章分类