简体   繁体   English

如何从通用列表递归获取范围内的所有元素?

[英]How can I get all elements in range from a generic List recursively?

Given a Generic type List (List),and two generic type objects: a,b: 给定一个通用类型列表(List),以及两个通用类型对象:a,b:

-Design an algorithm that returns a List that contains every element from the original list that belongs to the range [a,b). -设计一种算法,该算法返回一个列表,该列表包含原始列表中属于[a,b)范围的每个元素。

-The algorithm must include comparator E. -算法必须包含比较器E。

-The solution must be a "Divide and Conquer" algorithm. -解决方案必须是“分而治之”算法。

This is what i came up with: 这是我想出的:

private static <E extends Comparable<E>> List <E> Dominio(List<E> lista, E a, E b){

    return DominioAux(lista,a,b,0,lista.size()-1);
}

private static <E extends Comparable<E>> List <E> DominioAux(List<E> lista, E a, E b,Integer i, Integer j){

    List<E> res = new ArrayList<>();
    Integer m = (j-i)/2;
    E pm = lista.get(m);

    if (pm == a) {
        DominioAux(lista,a,b,m,j);
    } else if(pm==b) {
        DominioAux(lista,a,b,i,m-1);
    }

    if (pm.compareTo(a)<0) {
        res = DominioAux(lista,a,b,m,j);
    }   

    if (pm.compareTo(a)>0) {
        res = DominioAux(lista,a,b,i,m);
    }

    res = lista.subList(i, j);
    return res;     
}

The problem is I either get an "Index out of bounds exception" or an "Stack overflow error" when one of the ifs are executed. 问题是当执行其中一个if时,我得到了“索引超出范围异常”或“堆栈溢出错误”。

One possible solution using Divide and Conquer paradigm 一种使用分而治之范式的可能解决方案

private static <E extends Comparable<E>> List <E> DominioAux(List<E> lista, E a, E b,Integer i, Integer j){
    List<E> res = new ArrayList<>();

    if(i >= j) { //Check if the value of list[i] is in the range [a,b)
        if (lista.get(i).compareTo(a) >= 0 && lista.get(i).compareTo(b) < 0) {
            res.add(lista.get(i));
        }

        return res;
    }

    Integer m = (i + j) / 2;
    List<E> list1 = DominioAux(lista, a, b, i, m);
    List<E> list2 = DominioAux(lista, a, b, m + 1, j);

    res.addAll(list1);
    res.addAll(list2);

    return res;
}

One mistake in your approach is when calculating the m, m is supposed to be the middle if i and j then to calculate it you must add i and j not subtract i from j 您的方法中的一个错误是在计算m时,如果i和j被认为是m的中间值,则必须将i和j相加而不是从j中减去i来进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM