Java(给定两个整数数组num1和num2,返回它们的共同的元素)
时间: 2024-06-14 09:04:18 浏览: 12
以下是Java中给定两个整数数组num1和num2,返回它们的共同的元素的示例代码:
```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CommonElements {
public static int[] findCommonElements(int[] num1, int[] num2) {
Set<Integer> set1 = new HashSet<>();
for (int num : num1) {
set1.add(num);
}
List<Integer> commonElements = new ArrayList<>();
for (int num : num2) {
if (set1.contains(num)) {
commonElements.add(num);
}
}
int[] result = new int[commonElements.size()];
for (int i = 0; i < commonElements.size(); i++) {
result[i] = commonElements.get(i);
}
return result;
}
public static void main(String[] args) {
int[] num1 = {1, 2, 3, 4, 5};
int[] num2 = {4, 5, 6, 7, 8};
int[] commonElements = findCommonElements(num1, num2);
for (int num : commonElements) {
System.out.print(num + " ");
}
}
}
```
输出结果为:4 5
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)