java编程返回由两整型数组 arr1 和 arr2 中共同的元素组成的数组。
时间: 2023-06-13 18:06:17 浏览: 83
可以使用 Set 来实现这个功能,具体步骤如下:
1. 将数组 arr1 转换成 Set 集合 set1;
2. 遍历数组 arr2,对于其中的每个元素,判断是否在 set1 中出现过,如果出现过,则将其加入到结果集合中;
3. 将结果集合转换成数组并返回。
下面是代码实现:
```java
public static int[] findCommonElements(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) {
set1.add(num);
}
Set<Integer> resultSet = new HashSet<>();
for (int num : arr2) {
if (set1.contains(num)) {
resultSet.add(num);
}
}
int[] resultArray = new int[resultSet.size()];
int i = 0;
for (int num : resultSet) {
resultArray[i++] = num;
}
return resultArray;
}
```
使用示例:
```java
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
int[] result = findCommonElements(arr1, arr2);
System.out.println(Arrays.toString(result)); // 输出 [3, 4, 5]
```
注意:这个实现方法只适用于元素不重复的数组,如果数组中存在重复元素,需要使用 Map 或者计数排序等其他方法来实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)