[英]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.最后我想用文本显示最长的。
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:几点意见和建议:
sort()
sorts the array in increasing order, actually you do not have to check for decreasing elementssort()
按递增顺序对数组进行排序,实际上您不必检查递减元素 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:我按如下方式处理解决方案:
sequence
( what we want to find ) is a List
of at least 2 consecutive Integer
s (pair)sequence
(我们想要找到的)是一个至少包含 2个连续Integer
的List
(对)foundSequences
you need one result List
containing 0 or more List
sfoundSequences
您需要一个包含0 个或多个List
的结果List
current
and previous
elementcurrent
和previous
元素Logic applied (if):应用逻辑(如果):
current == previous + 1
, otherwise an existing consecutive sequence is brokencurrent == previous + 1
,否则现有连续序列被破坏sequence.size() > 1
, then it should be added to the result list (ie foundSequences
)sequence.size() > 1
,那么它应该被添加到结果列表中(即foundSequences
)previous == null
previous == null
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):迭代元素(循环):
current
element (iterating variable) current
元素(迭代变量)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.previous
will become null
to start a fresh collection.previous
一个元素将变为null
以开始新的集合。sequence
needs to be reset to null
to start a fresh collection.sequence
重置为null
以开始新的收集。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());
}
}
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.