您的位置:首页 > 其它

数组并集,交集,差集

2015-12-24 15:26 561 查看
import java.util.LinkedList;

public class ArrayTest {

/**
* @param args
*/
public static void main(String[] args) {
String[] str1={"aa","bb","cc","dd","cd"};
String[] str2={"ab","cd","bb","mm"};
System.out.println("---------------交集------------------");

String[] intersect_result=intersect(str1,str2);

for (String str : intersect_result) {
System.out.print(str+",");
}
System.out.println("");
System.out.println("---------------差集------------------");

String[] chaSet_result=chaSet(str1,str2);
for (String str : chaSet_result) {
System.out.print(str+",");
}
System.out.println("");
System.out.println("---------------并集------------------");

String[] bingSet_result=bingSet(str1,str2);
for (String str : bingSet_result) {
System.out.print(str+",");
}
}

//求两个数组的交集
public static String[] intersect(String[] arr1, String[] arr2) {
LinkedList<String> newL = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;
//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr1;
shorterArr = arr2;
}
for (String str : longerArr) {
if (!history.contains(str)) {
history.add(str);
}
}
for (String str : shorterArr) {
if (history.contains(str)) {
newL.add(str);
history.remove(str);
} else {
history.remove(str);
}
}

String[] result = {};
return newL.toArray(result);
}

//求两个数组的差集
public static String[] chaSet(String[] arr1, String[] arr2) {
LinkedList<String> newL = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;

//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr1;
shorterArr = arr2;
}
for (String str : longerArr) {
if (!history.contains(str)) {
history.add(str);
}
}
for (String str : shorterArr) {
if (history.contains(str)) {
history.remove(str);
} else {
newL.add(str);
history.remove(str);
}
}
for(String str : history){
newL.add(str);
}
String[] result = {};
return newL.toArray(result);
}

//求两个数组的并集
public static String[] bingSet(String[] arr1, String[] arr2) {
LinkedList<String> newL = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;

//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr1;
shorterArr = arr2;
}
for (String str : longerArr) {
if (!history.contains(str)) {
history.add(str);
}
}
for (String str : shorterArr) {
if (!history.contains(str)) {
history.add(str);
}
}

String[] result = {};
return history.toArray(result);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: