LeetCode 350. Intersection of Two Arrays II(Java)
来源:互联网 发布:淘宝店铺二级域名收费 编辑:程序博客网 时间:2024/06/08 17:56
原题:
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?
题意:
求两个数组的交集(包括重复出现的元素)。
思路:
1.遍历数组nums1,将其中的元素放入HashMap<Integer,Integer>
中进行统计;
2.新建ArrayList作为存储交集的元素(可重复元素);
3.遍历数组nums2,如果元素num2在map中出现过,则将其加入到list中,并将其对应的值-1;
4.将list转为数组返回即可。
代码:
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int num1:nums1){ if(!map.containsKey(num1)){ map.put(num1,1); }else{ map.put(num1,map.get(num1) + 1); } } List<Integer> list = new ArrayList<Integer>(); for(int num2:nums2){ if(map.containsKey(num2) && map.get(num2) > 0){ list.add(num2); map.put(num2,map.get(num2) - 1); } } int[] res = new int[list.size()]; for(int i = 0;i < list.size();i++){ res[i] = list.get(i); } return res; }}
- LeetCode 350. Intersection of Two Arrays II(Java)
- [LeetCode]Intersection of Two Arrays II(Java)
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- [Leetcode] 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- LeetCode - 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- leetcode-350. Intersection of Two Arrays II
- field module的on input和on request区别
- Qt 之 模仿迅雷 根据Url获取文件信息——上
- 二叉排序树操作及其树形
- spring学习笔记(11)
- day05笔记
- LeetCode 350. Intersection of Two Arrays II(Java)
- 【作业存档】最小生成树的练习
- Bootstrap学习总结笔记(23)-- 基本插件之轮播幻灯片
- Apache虚拟主机配置
- Springmvc与ssh2框架的优势和劣势
- CENTOS6.2安装jdk1.8,tomcat8,mysql5.5
- JSP判断radio是否选择和传值栗子(测试应聘人员能力自动计算分数)
- python基础(一):python语法一览
- Java基础Day04笔记