Java程序,用于对列表<list>中给定数字的连续编号进行分组

use*_*808 4 java algorithm math list

假设你有像这样的唯一数字

11,2,7,6,17,13,8,9,3,5,12
Run Code Online (Sandbox Code Playgroud)

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

[2,3]-[5,6,7,8,9]-[11,12,13]-[17]
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

dur*_*597 6

你的整体逻辑大多是正确的.但是,在执行过程中会遇到一些问题.

  1. 你得到一个数组索引超出范围的异常,因为你调用a[i+1]i = a.length.将循环条件更改为a.length - 1.
  2. ArrayList每次都需要使用一个新的内部,否则每个数组都将被清除.更改temp.clear();temp = new ArrayList<>();.
  3. 您需要将新列表初始化为第一个元素,而不是空列表.temp.add(a[0]);在开始temp.add(a[i+1])时添加,当您检测到需要新的子列表时.
  4. 您需要在最后添加最终列表,因为在循环结束时不会调用您的条件.

这是修改后的程序:

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class SubList {
    public static void main(String... args) {
        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<>();
        temp.add(a[0]);

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

        ListMain.add(temp);

        System.out.println(ListMain);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

[[2, 3], [5, 6, 7, 8, 9], [11, 12, 13], [17]]
Run Code Online (Sandbox Code Playgroud)