[英]Java program to group consecutive number from given numbers in a list<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();
}
}
你的整體邏輯大多是正確的。 但是,在執行過程中會遇到一些問題。
i = a.length
時調用a[i+1]
。 將循環條件更改為a.length - 1
。 ArrayList
,否則每個數組都將被清除掉。 改變temp.clear();
to 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]]
感謝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("================");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.