找出List集合中连续的数字和不连续的数字

需求

现在需要从数字1, 2, 3, 4, 6, 8, 9, 11, 12中,找出连续的数字和不连续的数字,得到的结果需要为1, 2, 3, 468, 911, 12,4个结果。

输出结果

连续的数字序列为: [1, 2, 3, 4]
不连续的数字: 6
连续的数字序列为: [8, 9]
连续的数字序列为: [11, 12]

工具类

public class Test {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 6, 8, 9, 11, 12);
        List<List<Integer>> continuousSequences = getNumberSequence(list);
        for (List<Integer> sequence : continuousSequences) {
            if (sequence.size() > 1) {
                System.out.println("连续的数字序列为: " + sequence);
            } else { // 单独的数字视为不连续
                System.out.println("不连续的数字: " + sequence.get(0));
            }
        }
    }
    
    private static List<List<Integer>> getNumberSequence(List<Integer> list) {
    	// 排序
    	Collections.sort(list);
    	
        // 找出连续和不连续的数字序列
        List<List<Integer>> continuousSequences = new ArrayList<>();
        List<Integer> currentSequence = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            if (i == 0 || list.get(i) - list.get(i - 1) == 1) {
                // 如果是第一个元素或者当前元素与前一个元素连续,则添加到当前序列
                currentSequence.add(list.get(i));
            } else {
                // 否则,将当前序列添加到连续序列列表,并开始新的序列
                if (!currentSequence.isEmpty()) {
                    continuousSequences.add(new ArrayList<>(currentSequence));
                }
                currentSequence.clear();
                currentSequence.add(list.get(i));
            }
        }

        // 不要忘记添加最后一个序列
        if (!currentSequence.isEmpty()) {
            continuousSequences.add(currentSequence);
        }

        return continuousSequences;
    }
}

欢迎关注公众号:慌途L
后面会慢慢将文章迁移至公众号,也是方便在没有电脑的情况下可以进行翻阅,更新的话会两边同时更新,大家不用担心!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值