Java – determines whether the list number is continuous

I work in Java I have an unordered list of 5 numbers, ranging from 0 to 100, without repetition I want to check whether three numbers are continuous without gap

example:

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

As for what I've tried, I haven't If I write it now, I may use the most naive method to sort the numbers, and then iterate to check whether the sequence exists

Solution

int sequenceMin(int[] set) {
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;
}

This sorts the array and uses the if statement above to find the desired sequence and return the first value

No sort:

(@ pace mentioned the desire of non sorting.) A valid Boolean array BitSet can be used for a limited range The iteration using nextsetbit is fast

int[] arr = {9,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");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>