Skip to content

Commit 7f29da4

Browse files
author
Andy
committed
set 唯一性 求并集
1 parent 79f961e commit 7f29da4

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

src/org/test/array/ArrayUnion.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.test.array;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
/**
7+
* @author Andy union ()方法来计算两个数组的并集
8+
*/
9+
public class ArrayUnion {
10+
public static void main(String[] args) {
11+
12+
String[] arr1 = { "1", "2", "3" };
13+
String[] arr2 = { "4", "5", "6" };
14+
String[] result_union = union(arr1, arr2);
15+
System.out.println("并集的结果如下:");
16+
17+
for (String str : result_union) {
18+
System.out.println(str);
19+
}
20+
}
21+
22+
public static String[] union(String[] arr1,String[]arr2){
23+
Set<String> set = new HashSet<String>();
24+
for(String str:arr1){
25+
set.add(str);
26+
}
27+
28+
for(String str:arr2){
29+
set.add(str);
30+
}
31+
32+
String [] result = {};
33+
return set.toArray(result);
34+
}
35+
}

0 commit comments

Comments
 (0)