Dart 程序将列表中给定数字的连续数字分组<list>

Sac*_*nel 1 algorithm math list dart

假设你有一个像这样的数字列表

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

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

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

Sac*_*nel 5

这是我对问题的解决方案:

List<List<int>> consecutive_groups(List<int> a) {
  a.sort();
  List<List<int>> result = [];
  List<int> temp = [];
  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 {
      result.add(temp);
      temp = [];
      temp.add(a[i + 1]);
    }
  }

  result.add(temp);

  return result;
}

Run Code Online (Sandbox Code Playgroud)