简体   繁体   English

如何从Java中的数组中提取最长的连续整数序列?

[英]How to extract longest consecutive sequence of integers from array in Java?

I want is to display all consecutive sequences from a given array of int s.我想要的是显示给定的int数组中的所有连续序列 Finally I want to display the longest one with text.最后我想用文本显示最长的

What I tried我试过的

  • I sorted the array and found all sequences.我对数组进行了排序并找到了所有序列。
  • I stored the found sequences into a new ArrayList.我将找到的序列存储到一个新的 ArrayList 中。

Below is only a small piece of code, because I know the rest doesn't work:下面只是一小段代码,因为我知道其余的不起作用:

int[] myArray = {202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5};
ArrayList<Integer> secuence = new ArrayList<>();
Arrays.sort(myArray);

for (int i = 0; i < myArray.length - 1; i++) {
  if ((myArray[i] + 1) == myArray[i + 1] || (myArray[i] - 1) == myArray[i - 1]) {
    secuence.add(myArray[i]);
  }
}

I tried many different ways, but can't figure out.我尝试了很多不同的方法,但无法弄清楚。

A couple remarks, suggestions:几点意见和建议:

  • As sort() sorts the array in increasing order, actually you do not have to check for decreasing elements由于sort()按递增顺序对数组进行排序,实际上您不必检查递减元素
  • For finding the "anything"est thing, you need to store the "anything"est thing found so far, and a current candidate.为了找到“最”的东西,你需要存储到目前为止找到的“最”的东西,以及当前的候选。 This applies to finding largest element or longest sequence of consecutive elements too这也适用于查找最大元素或最长连续元素序列
  • For dealing with subparts of an array, it is not necessary to make an actual copy of the elements, it is enough to store beginning index and ending index or length.对于处理数组的子部分,不需要制作元素的实际副本,存储开始索引和结束索引或长度就足够了。

Putting them together:将它们放在一起:

 var myArray = [202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5]; myArray.sort((a,b)=>ab); console.log("Sorted array:",...myArray); var longstart=0; var longlength=0; var currstart=0; while(currstart<myArray.length){ var currlength=0; while(currstart+currlength<myArray.length && myArray[currstart]+currlength==myArray[currstart+currlength]) currlength++; if(currlength>longlength){ longlength=currlength; longstart=currstart; } console.log("Sequence:",...myArray.slice(currstart,currstart+currlength)); currstart+=currlength; } console.log("Longest:",...myArray.slice(longstart,longstart+longlength));

This code is JavaScript so it can be run here, a Java variant (just with less printing) would look very similar:这段代码是 JavaScript,所以它可以在这里运行,Java 变体(只是打印较少)看起来非常相似:

int[] myArray = {202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5};
Arrays.sort(myArray);

int longstart=0;
int longlength=0;

int currstart=0;
while(currstart<myArray.length){
  int currlength=0;
  while(currstart+currlength<myArray.length
    && myArray[currstart]+currlength==myArray[currstart+currlength])
    currlength++;
  if(currlength>longlength){
    longlength=currlength;
    longstart=currstart;
  }
  currstart+=currlength;
}
for(int i=0;i<longlength;i++)
  System.out.print((i==0?"Longest: ":", ")+myArray[longstart+i]);

The key thing is to have the check work with a growing distance, so the fixed [i]+1==[i+1] check in your initial code became [i]+distance==[i+distance] .关键是让检查工作的距离越来越远,因此初始代码中固定的[i]+1==[i+1]检查变成[i]+distance==[i+distance]

I approached the solution as follows:我按如下方式处理解决方案:

Data structures数据结构

  1. a consecutive sequence ( what we want to find ) is a List of at least 2 consecutive Integer s (pair)一个连续的sequence我们想要找到的)是一个至少包含 2个连续IntegerList (对)
  2. to return all foundSequences you need one result List containing 0 or more List s要返回所有foundSequences您需要一个包含0 个或多个List的结果List
  3. to check for consecutive-ness you need the current and previous element要检查连续性,您需要currentprevious元素

Algorithm算法

Logic applied (if):应用逻辑(如果):

  1. Consecutive-ness is found if current == previous + 1 , otherwise an existing consecutive sequence is broken连续岬发现如果current == previous + 1 ,否则现有连续序列被破坏
  2. If a sequence has at least 2 elements, ie sequence.size() > 1 , then it should be added to the result list (ie foundSequences )如果一个序列至少有 2 个元素,即sequence.size() > 1 ,那么它应该被添加到结果列表中(即foundSequences
  3. Before the first element and after each broken sequence, the previous == null在第一个元素之前和每个断开的序列之后, previous == null
  4. After the last element there could be an open sequence with sequence.size() > 1 .最后一个元素之后,可能有一个带有sequence.size() > 1的开放序列。 If so, then this sequence is not broken, but completed and should be added to the result list (ie foundSequences )如果是这样,那么这个序列没有被破坏,而是完成并且应该被添加到结果列表中(即foundSequences

Iterating over elements (loop):迭代元素(循环):

  1. Use a for-each loop to process all elements of the (sorted!) array使用 for-each 循环处理(已排序!)数组的所有元素
  2. The for-loop automatically fills the current element (iterating variable) for 循环自动填充current元素(迭代变量)
  3. You must keep track of the previous element (thus initialized null before the loop).您必须跟踪previous元素(因此在循环之前初始化为null )。 It must archive the current element of each loop, so we can compare the next element against it.它必须存档每个循环的当前元素,以便我们可以将下一个元素与它进行比较。
  4. Unless the current element is not consecutive anymore (a break happened), then the previous will become null to start a fresh collection.除非当前元素不再连续(发生中断),否则previous一个元素将变为null以开始新的集合。
  5. In case of a break the currently found sequence may be added to the result.中断的情况下,可以将当前找到的序列添加到结果中。 Then the sequence needs to be reset to null to start a fresh collection.然后需要将sequence重置为null以开始新的收集。
  6. After the last element was checked and the loop ended, there could be still a sequence (that was not yet broken).在检查完最后一个元素并结束循环之后,可能还有一个序列(尚未中断)。 This needs to be added to the result.这需要添加到结果中。 8. 8.

Source来源

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class ConsecutiveSequenceFinder {

    private int[] unsortedNumbers;

    public ConsecutiveSequenceFinder(int[] numbers) {
        this.unsortedNumbers = numbers;
    }

    public int[] sorted() {
        int[] sortedNumbers = Arrays.copyOf(this.unsortedNumbers, this.unsortedNumbers.length);
        Arrays.sort(sortedNumbers);
        return sortedNumbers;
    }

    public List<List<Integer>> findSequences() {
        // one sequence is List of integers; thus list of sequences is list of list of integers
        List<List<Integer>> foundSequences = new ArrayList<>();
        // first we sort the array
        int[] ascending = this.sorted();
        // this working variable will hold the currently found sequence
        List<Integer> sequence = new ArrayList<Integer>();
        Integer previous = null;
        System.out.println("Finding sequences ..");
        for (int current : ascending) {
            // check if current value is first or one more than (consecutive to) previous
            if (previous == null || current == previous + 1) {
                sequence.add(current);
                previous = current;
            } else {
                System.out.printf("\tsequence of %d consecutive is broken at: %d\n", sequence.size(), current);
                // if sequence found (at least a pair) then add
                if (sequence.size() > 1) {
                    foundSequences.add(sequence);
                }
                // and finally prepare a new sequence, to collect fresh again
                sequence = new ArrayList<>();
                previous = null;
            }
        }
        // if sequence left, then add
        if (sequence.size() > 1) {
            System.out.printf("\tsequence of %d consecutive was completed with last array element\n", sequence.size());
            foundSequences.add(sequence);
        }
        return foundSequences;
    }

    public static void main (String[] args) throws java.lang.Exception {
        // demo numbers
        int[] values = {202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5};
        // starting demo
        System.out.println("Input: " + Arrays.toString(values));
        ConsecutiveSequenceFinder finder = new ConsecutiveSequenceFinder(values);
        System.out.println("Sorted: " + Arrays.toString(finder.sorted()));
        List<List<Integer>> foundSequences = finder.findSequences();
        System.out.println("Found sequences: " + foundSequences.size());
        // print for each sequence the size and its elements
        for (List<Integer> sequence : foundSequences) {
            System.out.printf("\t %d elements: %s\n",sequence.size(), sequence.toString());
        }
        // check for each sequence if it is the longest
        List<Integer> longestSequence = new ArrayList<>();
        for (List<Integer> sequence : foundSequences) {
            if (sequence.size() > longestSequence.size()) {
                longestSequence = sequence;
            }
        }
        System.out.printf("Longest sequence has %d elements: %s\n",longestSequence.size(), longestSequence.toString());
    }
}

Actual Output实际产量

Input: [202, 203, 204, 205, 206, 100, 1, 3, 200, 2, 4, 201, 5]
Sorted: [1, 2, 3, 4, 5, 100, 200, 201, 202, 203, 204, 205, 206]
Finding sequences ..
    sequence of 5 consecutive is broken at: 100
    sequence of 7 consecutive was completed with last array element
Found sequences: 2
     5 elements: [1, 2, 3, 4, 5]
     7 elements: [200, 201, 202, 203, 204, 205, 206]
Longest sequence has 7 elements: [200, 201, 202, 203, 204, 205, 206]

Process finished with exit code 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 [java]最长连续整数序列,调试 - [java]Longest consecutive integers sequence, debug 编写一个程序来查找整数数组中最长的连续序列的长度? - Write a program to find length of longest consecutive sequence in array of integers? 从给定的未排序整数数组中查找最长连续元素序列的长度 - Find the length of the longest consecutive elements sequence from a given unsorted array of integers 优化此解决方案:最长连续的不同整数序列 - Optimizing this solution: Longest consecutive distinct sequence of integers 如何从int []数组(Java)打印最长的数字序列 - How to print the longest sequence of numbers from int[] array (Java) 在整数数组中找到最长连续序列的长度的程序的时间复杂度是多少? - What is the time-complexity of a program that finds the length of the longest consecutive sequence in an array of integers? 如何从java中的字符串中提取最长的子字符串(具有不同的连续字符) - how to extract longest sub string (having distinct consecutive character) from a string in java 从字符串中提取特定的整数序列 Java - Extract a specific sequence of integers from a string Java 如何找到连续自然继承者的最长序列? - How to find the longest sequence of consecutive natural successors? Java 查找数组的最长序列 - Java finding longest sequence of an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM