博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)
阅读量:4649 次
发布时间:2019-06-09

本文共 1966 字,大约阅读时间需要 6 分钟。

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?

 

 


 

题目标签:Hash Table

  题目给了我们两个array, 让我们找到相交的数字,这一题与 #349 一样,只是可以包括重复的数字。

  所以利用HashMap 把 nums1 的数字和 出现次数存入;

  比较nums2 和 map1 把相交的数字 和 次数 存入 intersect;

  最后把intersect 里的 数字 按照它的出现次数 存入 int[] res。

 

 

 

Java Solution:

Runtime beats 23.67% 

完成日期:06/05/2017

关键词:HashMap

关键点:利用两个HashMap

1 class Solution  2 { 3     public int[] intersect(int[] nums1, int[] nums2)  4     { 5         HashMap
map1 = new HashMap<>(); 6 HashMap
intersect = new HashMap<>(); 7 int[] res; 8 int len = 0; 9 int pos = 0;10 11 // store nums1 numbers into map112 for(int n: nums1)13 map1.put(n, map1.getOrDefault(n, 0) + 1);14 15 16 // compare nums2 with map1, store intersected numbers into intersect17 for(int n: nums2)18 {19 if(map1.containsKey(n))20 {21 intersect.put(n, intersect.getOrDefault(n, 0) + 1);22 len++;23 24 map1.put(n, map1.get(n) - 1);25 26 if(map1.get(n) == 0)27 map1.remove(n);28 }29 30 }31 32 res = new int[len];33 34 for(int n: intersect.keySet())35 {36 for(int i=0; i

参考资料:N/A

 

LeetCode 题目列表 - 

转载于:https://www.cnblogs.com/jimmycheng/p/7797168.html

你可能感兴趣的文章
CentOS搭建SVN服务器
查看>>
WMS与MES集成
查看>>
设置SQLServer数据库内存
查看>>
Java随机3-斐波拉切函数
查看>>
Linux下undefined reference to ‘pthread_create’问题解决 zz
查看>>
P1638 逛画展(直尺法)
查看>>
常用正则表达式
查看>>
github.com/oschwald/maxminddb-golang 安装报错
查看>>
算法复杂度的快慢
查看>>
Java EE中的重新验证(java.util.regex.Pattern)
查看>>
Java从入门到精通——数据库篇Mongo DB 导出,导入,备份
查看>>
Windows 平台下 Go 语言的安装和环境变量设置
查看>>
最近在练习爬虫,分享一些简单入门的知识
查看>>
实验二:编写输出"Hello World!"
查看>>
HDU 1251 统计难题
查看>>
vim深入研究
查看>>
数组中冒泡排序、直接选择排序、反序排序原理与区别
查看>>
原生js实现ajax
查看>>
1067 Sort with Swap(0, i) (25 分)
查看>>
UIButton 用法
查看>>