歌者悦

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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);
}

}

posted on 2015-12-24 15:26  歌者悦  阅读(256)  评论(0)    收藏  举报