确定列表编号是否是连续的 [英] Determining if a list numbers are sequential

查看:99
本文介绍了确定列表编号是否是连续的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java.我有5个数字的无序列表,范围是0-100,没有重复.我想检测3个数字是否连续且无间隔.

I'm working in Java. I have an unordered list of 5 numbers ranging from 0-100 with no repeats. I'd like to detect if 3 of the numbers are sequential with no gap.

示例:

[9,12,13,11,10] true
[17,1,2,3,5] true
[19,22,23,27,55] false

至于我尝试过的,什么都没有.如果我现在要编写它,我可能会采用最幼稚的方法来对数字进行排序,然后迭代检查序列是否存在.

As for what I've tried, nothing yet. If I were to write it now, I would probably go with the most naive approach of ordering the numbers, then iteratively checking if a sequence exists.

推荐答案

int sequenceMin(int[] set) {
    int[] arr = Arrays.copy(set);
    Arrays.sort(arr);
    for (int i = 0; i < arr.length - 3 + 1; ++i) {
        if (arr[i] == arr[i + 2] - 2) {
            return arr[i];
        }
    }
    return -1;
}

这将对数组进行排序,并使用上面的if语句查找所需的序列,并返回第一个值.

This sorts the array and looks for the desired sequence using the if-statement above, returning the first value.

不进行排序:

Without sorting:

(@ Pace提到了不进行排序的愿望.)在有限范围内可以使用有效的布尔数组" BitSet. nextSetBit的迭代速度很快.

(@Pace mentioned the wish for non-sorting.) A limited range can use an efficient "boolean array", BitSet. The iteration with nextSetBit is fast.

    int[] arr = {9,12,13,11,10};
    BitSet numbers = new BitSet(101);
    for (int no : arr) {
        numbers.set(no);
    }
    int sequenceCount = 0;
    int last = -10;
    for (int i = numbers.nextSetBit(0); i >= 0; i = numbers.nextSetBit(i+1)) {
        if (sequenceCount == 0 || i - last > 1) {
            sequenceCount = 1;
        } else {
            sequenceCount++;
            if (sequenceCount >= 3) {
                System.out.println("Sequence start: " + (last - 1));
                break;
            }
        }
        last = i;
    }
    System.out.println("Done");

这篇关于确定列表编号是否是连续的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆