我想从数组中获取5个数字的序列。 例如:
int arr1[] = {3,88,99,5,4,6,22,32,7,45}; // array where there is the sequence 3,4,5,6,7
Vector<Integer> myVec = new Vector<Integer>(); // vector wehre to save the sequence
现在我需要做什么才能从该数组中获取序列? 我这里有一个代码,但它无法正常工作:
for(int i = 0; i < arr1.length -1; i++) {
int a = arr1[i];
int b = arr1[i+1];
int c = b - a;
if(c == 1) {
myvec.add(arr1[i]);
}
}
我应该如何更改代码来解决此问题?
答案 0 :(得分:1)
此程序将打印阵列中的所有序列没有分类阵列。您可以选择包含大小的列表..如果您想要匹配5序列,请获取大小为5的列表。希望此帮助。 (根据您的需要进行修改。)
import java.util.ArrayList;
import java.util.List;
public class Sequence {
private static int arr1[] = { 3, 88, 99, 5, 4, 6, 22, 32, 7, 45 };
private static int findNextInSequence(int start) {
int next = -1;
for(int i = 0; i < arr1.length; i++){
if((start - arr1[i]) == -1){
next = arr1[i];
}
}
return next;
}
public static void main(String[] args) {
for (int i = 0; i < arr1.length; i++) {
List<Integer> sequence = new ArrayList<Integer>();
int nextSequence = arr1[i];
do{
sequence.add(nextSequence);
nextSequence = findNextInSequence(nextSequence);
} while(nextSequence != -1);
System.out.println(sequence);
}
}
}
答案 1 :(得分:0)
您的代码检查arr1数组中两个连续值之间的差异。因为它没有排序,它的工作原理如下:
88-3 !=1 (value not added)
99-88 !=1 (value not added)
5-99 !=1 (value not added)
...
45-7 !=1 (value not added).
您必须确保首先对数组中的值进行排序。使用Arrays.sort()并在排序数组上应用该方法。这应该添加值:3,4,5,6,但它不会添加7(因为它在循环执行时将是你的arr [i + 1]值。
4-3 ==1 (value added)
5-4 ==1 (value added)
6-5 ==1 (value added)
7-6 ==1 (value added, but it is only number 6 that is added!)
答案 2 :(得分:0)
您应该将连续计数最多计算为5,并将结果放入ArrayList
而不是Vector
。因为ArrayList
比Vector
更有效。尝试,
int arr1[] = {3, 88, 99, 5, 4, 6, 22, 32, 7, 45, 11, 12, 13, 14, 15};
List<Integer> myVec = new ArrayList<>();
Arrays.sort(arr1);
int count = 0;
int lastValue = 0;
for (int i = 0; i < arr1.length - 1; i++) {
if (arr1[i + 1] - arr1[i] == 1) {
count++;
System.out.println(arr1[i]);
lastValue = arr1[i + 1];
} else {
System.out.println(count);
if (count >= 4) {
for (int j = 0; j <= count; j++) {
myVec.add(lastValue - 4 + j);
}
}
count = 0;
}
}
System.out.println(myVec);