JAVA 获取一组数据中的多组连续数据集合

给定一组数据,返回该数据中多组连续数据集合。

例如:

        给定  [2, 3, 4, 6, 8, 10, 11, 12, 15, 16]

        返回: [2, 3, 4],[6],[8],[10,11,12],[15,16]

使用java语言写的,逻辑很简单,应该都能看得懂,就直接贴代码了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * 获取列表中多组连续数据
 * @param list 原数据
 * @return 多组连续数据
 */
public static List<List<Integer>> getSerialNumList(List<Integer> list) {
    List<List<Integer>> resultList = new ArrayList<>();
    List<Integer> arrList = new ArrayList<>();
    resultList.add(arrList);
    if (list.size() == 1) {
        resultList.get(resultList.size() - 1).add(list.get(0));
        return resultList;
    }
    for (int i = 0; i < list.size(); i++) {
        Integer nextNum = list.get(i + 1);
        Integer nowNum = list.get(i);
        if (nextNum - nowNum != 1) {
            resultList.get(resultList.size() - 1).add(nowNum);
            arrList = new ArrayList<>();
            resultList.add(arrList);
        } else {
            arrList.add(nowNum);
        }
        if (i + 1 == list.size() - 1 ) {
            arrList.add(nextNum);
            break;
        }
    }
    return resultList;
}

 

1
2
3
4
5
6
public static void main(String[] args) {
    Integer[] arr = {2, 3, 4, 6, 8, 10, 11, 12, 15, 16};
    List<Integer> list = new ArrayList<>(Arrays.asList(arr));
    List<List<Integer>> serialNumList = getSerialNumList(list);
    serialNumList.forEach(System.out::println);
}

 

posted @   锐洋智能  阅读(991)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过
历史上的今天:
2018-04-29 Java.lang.Character类
2018-04-29 Java Comparator字符排序(数字、字母、中文混合排序)
点击右上角即可分享
微信分享提示