一尘不染

如何在Java中进行合并,相交,差异和反向数据

java

我想在Java中进行联合,相交,差异和反向操作。

首先我有2个实例 ArrayList<Integer>

a = [0,2,4,5,6,8,10]
b = [5,6,7,8,9,10]

联盟b应该返回 c = [0,2,3,4,5,6,7,8,9,10]

a相交b应该返回 c = [5,8,10]

a偏差b应该返回 c = [0,2,3,4]

相反a = [10,8,6,5,4,2,0]

这样的事情。

如何在Java中实现该方法?

更新:我必须从以下模板开始:

package IntSet;
import java.util.ArrayList;
import java.util.Collection;


public class IntSet {

private ArrayList<Integer> intset;

public IntSet(){
    intset = new ArrayList<Integer>();
}

public void insert(int x){
    intset.add(x);
}

public void remove(int x){
    //implement here
    intset.indexOf(x);
}

public boolean member(int x){
    //implement here
    return true;
}

public IntSet intersect(IntSet a){
    //implement here
    return a;
}

public IntSet union(IntSet a){
    //implement here
    return a;
}

public IntSet difference(IntSet a){
    //implement here
    IntSet b = new IntSet();
    return b; 
}

阅读 242

收藏
2020-03-24

共2个答案

一尘不染

//Union 
List<Integer> c = new ArrayList<Integer>(a.size() + b.size());
addNoDups(c,a);
addNoDups(c,b);

private void addNoDups(List<Integer> toAddTo,List<Integer> iterateOver) {
    for(Integer num:iterateOver){
        if(toAddTo.indexOf(num) == -1) {
            toAddTo.add(num);
        }
    }
}

//intersection
List<Integer> c = new ArrayList<Integer> (a.size() > b.size() ?a.size():b.size());
c.addAll(a);
c.retainAll(b);

//difference a-b
List<Integer> c = new ArrayList<Integer> (a.size());
c.addAll(a);
c.removeAll(b);
2020-03-24
一尘不染

首先,你描述的操作(反向操作除外)是集合操作,而不是列表操作,因此请使用HashSet或(如果需要订购)TreeSet。

    Set<Integer> a = new TreeSet<Integer>(Arrays.asList(new Integer[]{0,2,4,5,6,8,10}));
    Set<Integer> b = new TreeSet<Integer>(Arrays.asList(new Integer[]{5,6,7,8,9,10}));

    //union
    Set<Integer> c = new TreeSet<Integer>(a);
    c.addAll(b);
    System.out.println(c);

    //intersection
    Set<Integer> d = new TreeSet<Integer>(a);
    d.retainAll(b);
    System.out.println(d);

    //difference
    Set<Integer> e = new TreeSet<Integer>(a);
    e.removeAll(b);
    System.out.println(e);

    //reverse
    List<Integer> list = new ArrayList<Integer>(a);
    java.util.Collections.reverse(list);
    System.out.println(list);
2020-03-24