int数组交并差集

2017/06/08 问题一箩筐
public int[] operate(int[] a, int[] b, String operation){
    
    Set<Integer> aSet = new TreeSet<>(Arrays.stream(a).boxed().collect(Collectors.toList()));
    Set<Integer> bSet = new TreeSet<>(Arrays.stream(b).boxed().collect(Collectors.toList()));
    Set<Integer> resultSet = new TreeSet<>();
    switch (operation) {
        case "UNION":			//并集
            aSet.addAll(bSet);
            resultSet = aSet;
            break;
        case "INTERSECTION":	//交集
            resultSet.addAll(aSet);
            resultSet.retainAll(bSet);
            break;
        case "SYMMETRIC DIFFERENCE":	//差集
            resultSet.addAll(aSet);
            resultSet.removeAll(bSet);
            Set<Integer> removeSet = new TreeSet<>();
            removeSet.addAll(bSet);
            removeSet.removeAll(aSet);
            resultSet.addAll(removeSet);
            break;

        default:
            break;
    }
    int[] resultInt = new int[resultSet.size()];
    Iterator<Integer> it = resultSet.iterator();
    int i = 0;
    while (it.hasNext()) {
        resultInt[i] = it.next();
        i++;
    }
    return resultInt;
}

Search

    欢迎关注我的微信公众号

    Yannis的程序人生

    Table of Contents