/**
* 通过数组操作集合,实现并,交,差
* @author BreAthe
*
*/
class SetOperator {
/**
* 实现数组集合setOne,setTwo的交运算
* @param setOne
* @param setTwo
*/
public void intersection(int[] setOne, int[] setTwo) {
for(int i = 0; i < setTwo.length; i++) {//逐个考察setTwo中的元素
for(int j = 0; j < setOne.length; j++) {
if(setOne[j] == setTwo[i]) {
System.out.print(setOne[j] + " ");
break;
}
}
}
}
/**
* 实现数组集合setOne,setTwo的差运算
* setOne - setTwo
* @param setOne
* @param setTwo
*/
public void difference(int[] setOne, int[] setTwo) {
for(int i = 0; i < setTwo.length; i++) {
boolean flag = false;
for(int j = 0; j < setOne.length; j++) {
if(setOne[j] == setTwo[i]) {
flag = true;
break;
}
}
if(!flag) {
System.out.print(setTwo[i] + " ");
}
}
}
/**
* 实现数组集合setOne,setTwo的并运算
* @param setOne
* @param setTwo
*/
public void union(int[] setOne, int[] setTwo) {
for(int i = 0; i < setOne.length; i++) {
System.out.print(setOne[i] + " ");
}
for(int i = 0; i < setTwo.length; i++) {//逐个考察setTwo中的元素
boolean flag = false;
for(int j = 0; j < setOne.length; j++) {
if(setTwo[i] == setOne[j]) {
flag = true;
break;
}
}
if(!flag) {
System.out.print(setTwo[i] + " ");
}
}
}
public void prset(int[] set) {
for(int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
System.out.println();
}
public class SetOperatorTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] one = {2, 5, 7, 8, 10, 12, 15, 17, 20};
int[] two = {3, 5, 7, 9, 13};
SetOperator so = new SetOperator();
System.out.println("集合1为:");
so.prset(one);
System.out.println("集合2为:");
so.prset(two);
System.out.println("两个集合的并为:");
so.union(one, two);
System.out.println("\n两个集合的交为:");
so.intersection(one, two);
System.out.println("\n集合1和集合2的差为:");
so.difference(one, two);
}
}
数组实现集合的并,交,差
最新推荐文章于 2021-12-11 20:36:48 发布