Java 中找出两个数组的交集370
在 Java 中,找出两个数组的交集是一个常见的问题。交集是指同时存在于两个数组中的元素。
使用 Set
使用 Set 数据结构是找出交集的最简单方法之一。Set 是一个无序集合,它不会存储重复的元素。我们可以将两个数组都添加到 Set 中,然后使用 Set 的 retainAll 方法来保留两个数组的交集。
import ;
import ;
import ;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
// 将数组添加到 Set 中
Set set1 = new HashSet((arr1));
Set set2 = new HashSet((arr2));
// 保留交集
(set2);
// 打印交集
(set1);
}
}
使用双指针
如果我们知道两个数组都是升序排列的,我们可以使用双指针算法。我们从两个数组的开头开始,如果当前元素相等,则将其添加到交集中。如果一个元素较小,则我们移动该元素对应的指针。继续此过程,直到到达两个数组的末尾。
public static int[] intersection(int[] arr1, int[] arr2) {
int m = ;
int n = ;
int[] intersection = new int[m + n];
int i = 0, j = 0, k = 0;
while (i < m && j < n) {
if (arr1[i] == arr2[j]) {
intersection[k++] = arr1[i];
i++;
j++;
} else if (arr1[i] < arr2[j]) {
i++;
} else {
j++;
}
}
return (intersection, 0, k);
}
使用 HashMap
我们可以使用 HashMap 来找出数组的交集。我们将一个数组的元素作为 Key,另一个数组的元素作为 Value。然后,遍历第一个数组,如果某个元素在 HashMap 中,则将其添加到交集中。这种方法的时间复杂度为 O(m + n),其中 m 和 n 是两个数组的长度。
public static int[] intersection(int[] arr1, int[] arr2) {
Map map = new HashMap();
for (int num : arr1) {
(num, 1);
}
List intersection = new ArrayList();
for (int num : arr2) {
if ((num)) {
(num);
}
}
return ().mapToInt(i -> i).toArray();
}
在 Java 中找出两个数组的交集有多种方法。选择最适合您特定要求的方法。使用 Set 的方法是最简单的,但仅适用于无重复元素的数组。使用双指针的方法是最有效的,但要求数组是有序的。使用 HashMap 的方法是最通用的,适用于任何类型的数组。
2024-12-07
上一篇:使用 Java 捕获数据包
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html