use*_*808 4 java algorithm math 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();
    }
}
你的整体逻辑大多是正确的.但是,在执行过程中会遇到一些问题.
a[i+1]时i = a.length.将循环条件更改为a.length - 1.ArrayList每次都需要使用一个新的内部,否则每个数组都将被清除.更改temp.clear();到temp = new ArrayList<>();.temp.add(a[0]);在开始temp.add(a[i+1])时添加,当您检测到需要新的子列表时.这是修改后的程序:
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);
    }
}
输出:
[[2, 3], [5, 6, 7, 8, 9], [11, 12, 13], [17]]