有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

算法Java程序从列表中给定的数字中分组连续数<list>

假设你得到了唯一的数字,比如

11,2,7,6,17,13,8,9,3,5,12

结果将是一组包含子列表的数字列表,即:

[2,3]-[5,6,7,8,9]-[11,12,13]-[17]

我采用这种方法来解决以下问题:

int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };

Arrays.sort(a);
List<List<Integer>> ListMain = new ArrayList<>();
List<Integer> temp = new ArrayList<>();

for (int i = 0; i < a.length; i++) {
    if (a[i + 1] == a[i] + 1) {
        temp.add(a[i + 1]);
    } else {
        ListMain.add(temp);
        temp.clear();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    谢谢Garis M Suero的建议,之后我得到了答案

        int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
    
        Arrays.sort(a);
    
        List<List<Integer>> listMain = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<>();
    
        for (int i = 0; i < a.length; i++) {
            if ((i + 1<a.length)&&( a[i] + 1==a[i + 1])) {
                temp.add(a[i]);
            } else {
                temp.add(a[i]);
                listMain.add(temp);
                temp  = new ArrayList<>();
            }
    
        }
    
        for (List<Integer> lstI : listMain) {
                for (Integer i : lstI) {
                    System.out.println(i);
                }
            System.out.println("================");
         }