当前位置:网站首页>349、两个数组的交集
349、两个数组的交集
2022-04-23 10:11:00 【Popuessing's Jersey】
题意:给定两个数组,编写一个函数来计算它们的交集
解决问题之前的一些小知识:
HashSet是实现Set接口,也就是Set的实现类,由哈希表支持的(实现一个HashMap实例)
源码:
private transient HashMap<E,Object> map;
//默认构造器
public HashSet() {
map = new HashMap<>();
}
//将传入的集合添加到HashSet的构造器
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
//明确初始容量和装载因子的构造器
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
//仅明确初始容量的构造器(装载因子默认0.75)
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
public class Lianggeshuzudejiaji {
public int[] intersection(int[]nums1 ,int[] nums2){
//如果有其中一个数组为空,返回空集合
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length==0){
return new int[0];
}
//创建集合存放元素
Set<Integer> set = new HashSet<>();
Set<Integer> reSet = new HashSet<>();
//遍历数组1
for (int i: nums1) {
set.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该数组
for (int i: nums2) {
//如果出现数组1中存在的元素,将重复元素放入新的集合中
if (set.contains(i)){
reSet.add(i);
}
}
//根据数组2判断重复后的集合大小,创建一个新的数组
int [] resArr = new int[reSet.size()];
int index = 0;
//取出集合中的元素,将结果转为数组
for (int i : reSet) {
resArr[index++] = i;
}
return resArr;
}
public static void main(String[] args) {
int [] nums1 = {4,2,2,1};
int [] nums2 = {2,3,4};
Lianggeshuzudejiaji lianggeshuzudejiaji =new Lianggeshuzudejiaji();
int [] res = lianggeshuzudejiaji.intersection(nums1,nums2);
for (int x:res) {
System.out.print(x+" ");
}
}
输出结果:
2 4
版权声明
本文为[Popuessing's Jersey]所创,转载请带上原文链接,感谢
https://blog.csdn.net/CoCo629vanilla/article/details/121475581
边栏推荐
猜你喜欢
Construire neuf capacités de fabrication agile à l'ère métacosmique
【无标题】
2022 mobile crane driver test question bank simulation test platform operation
Comparative analysis of meta universe from the dimension of knowledge dissemination
Read LSTM (long short term memory)
2022年上海市安全员C证考试题库及答案
Solve the problem of installing VMware after uninstalling
2022年制冷与空调设备运行操作考试练习题及模拟考试
【省选联考 2022 D2T1】卡牌(状态压缩 DP,FWT卷积)
Question bank and answers of Shanghai safety officer C certificate examination in 2022
随机推荐
Juc并发编程07——公平锁真的公平吗(源码剖析)
杰理之有时候发现内存被篡改,但是没有造成异常,应该如何查找?【篇】
杰理之系统事件有哪些【篇】
Arm debugging (1): two methods to redirect printf to serial port in keil
failureForwardUrl与failureUrl
Ansible playbook syntax and format automate cloud computing
通过流式数据集成实现数据价值(4)-流数据管道
Sim Api User Guide(5)
Sim Api User Guide(6)
实践六 Windows操作系统安全攻防
Rain produces hundreds of valleys, and all things grow
DBA常用SQL语句(2)— SGA和PGA
Chapter 3 enable and adjust the size of IM column storage (im-3.1)
構建元宇宙時代敏捷制造的九種能力
Yarn资源调度器
LeetCode 1249. Minimum Remove to Make Valid Parentheses - FB高频题1
Leetcode22:括号生成
第二章 In-Memory 体系结构 (IM-2.2)
Solve the problem of installing VMware after uninstalling
LeetCode-608. Tree node