【发布时间】:2014-12-21 14:32:26
【问题描述】:
我有一个按顺序排列的整数列表。 我想将连续整数组作为数组,每个组的第一个和最后一个整数。
例如,对于 (2,3,4,5,8,10,11,12,15,16,17,18,25) 我想得到一个包含这些数组的列表:[2,5] [ 8,8] [10,12] [15,18] [25,25]
这是我的代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyRangesTest {
public static void main(String[] args) {
//create list of integers
List<Integer> list=Arrays.asList(2,3,4,5,8,10,11,12,15,16,17,18,25);
System.out.println("list:" + list);
//create a list with integers where a new sequense of consecutive integers starts or ends
List<Integer> sublistsStarsAndEnds= new ArrayList<>();
sublistsStarsAndEnds.add(list.get(0));//1st line (always in sublistsStarsAndEnds list)
for (int i=1; i<list.size()-1; i++){
if (list.get(i)>1+list.get(i-1)){
sublistsStarsAndEnds.add(list.get(i-1));
sublistsStarsAndEnds.add(list.get(i));
}
}
sublistsStarsAndEnds.add(list.get(list.size()-1));//last line (always in sublistsStarsAndEnds list)
System.out.println("sublistsStarsAndEnds: " + sublistsStarsAndEnds);//present the result
//create list with arrays that represents start and end of each subrange of consequent integers
List<Integer[]> ranges= new ArrayList<>();
for (int i=0; i<sublistsStarsAndEnds.size()-1; i=i+2){
Integer[] currentrange=new Integer[2];
currentrange[0]=sublistsStarsAndEnds.get(i);
currentrange[1]=sublistsStarsAndEnds.get(i+1);
ranges.add(currentrange);//present the result
}
//present the result
String rangestxt="";//create result text
for (int i=0; i<ranges.size(); i++){
rangestxt=rangestxt+ranges.get(i)[0]+ " " + ranges.get(i)[1]+ " ";
}
System.out.println("ranges: " + rangestxt);//present the result
}
}
此代码适用于我想要的一般情况,但是当最后一个序列只有 1 个整数时,它无法获得正确的结果。
例如当使用这个列表时:(2,3,4,5,8,10,11,12,15,16,17,18,25) 而不是获取范围 [2,5] [8, 8] [10,12] [15,18] [25,25] 我们得到范围 [2,5] [8,8] [10,12] [15,25]。
问题在于检测范围的开始或结束位置。在我的代码中,这些地方存储在sublistsStarsAndEnds 列表中。这里不是得到 [2, 5, 8, 8, 10, 12, 15, 15, 25, 25],而是得到 [2, 5, 8, 8, 10, 12, 15, 25]。
我尝试更正代码,但效果不佳。
有什么建议吗?
附:有人想得到我想要的结果,并在这里问了一个 Python 问题“Identify groups of continuous numbers in a list 但我不懂 Python,所以我尝试了自己的编码。
【问题讨论】:
-
好问题。点赞!!