簡體   English   中英

Java程序,用於對列表中給定數字的連續編號進行分組<list>

[英]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();
    }
}

你的整體邏輯大多是正確的。 但是,在執行過程中會遇到一些問題。

  1. 你得到一個數組索引超出范圍的例外,因為你在i = a.length時調用a[i+1] 將循環條件更改為a.length - 1
  2. 每次都需要使用一個新的內部ArrayList ,否則每個數組都將被清除掉。 改變temp.clear(); to 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);
    }
}

輸出:

[[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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM