我对编程非常陌生,这是我的第一篇文章。
我正在尝试创建一个方法,它接受一个数组(从文本文件中),比较序列中的值,以找到最长的不递减序列(值,,而不是索引)。
例如,在数组2 3 4 1 5 0 2 3 4 4 1 4 4 2 3 3 4 5 5中(而不是5)。
我一直试图遵循这篇文章最长增长序列,但它使用ArrayLists (我不允许在分配中使用)
下面是我到目前为止掌握的代码:
public double brightSequenceNonDec()throws FileNotFoundException{
double[] numbersInSequence = new double[numbersOfLines];
for (int i = 0; i < listElements.length; i++) {
for (int k = i + 1; k < listElements.length; k++) {
if (listElements[i].brightness()<=listElements[k].brightness()) {
numbersInSequence[0] = listElements[i].brightness();
}
}
}
任何关于我做错了什么的指示都会受到极大的感谢。
发布于 2017-08-01 16:39:46
因为这是一项任务,我不会给你详细的答案,而是提供一些指点。
把你的问题分成子问题也许是个好主意。这也将使人们更容易了解正在发生的事情。
一旦您的循环完成,您可以使用System.arraycopy() (或者您自己的循环,如果禁止的话)将所有值从最长的序列复制到一个新的数组中。毕竟,您现在知道了最长序列的起点,并且知道了该序列的长度。这意味着您甚至知道目标数组的初始大小。
发布于 2017-08-01 16:45:20
public class LongestIncreasingSequence {
double[] longestSequence(double input[]) {
// variable start and end will store the starting index and ending index
// of array
// variable max will store the length of sequence and compare it to the
// older length
// length will store the maximum length
int start = 0, end = 0, length = 0, index, max = 0;
int arrayLength = input.length;
for (index = 1; index < arrayLength; index++) {
if (input[index] >= input[index - 1]) {
max++;
}
else {
if (max > length) {
length = max;
end = index;
start = end - length - 1;
}
max = 0;
}
}
// this condition will work when the last element is also the part of
// the longest sequence
if (max > length) {
length = max;
end = index;
start = end - length - 1;
}
int resultLength = end - start;
double result[] = new double[resultLength];
for (index = 0; index < resultLength; index++, start++) {
result[index] = input[start];
}
return result;
}
}
发布于 2017-08-01 16:50:09
在这里你有:
public static int[] longestNonDecreasingSequence(int[] fullSequence) {
int[] maxSequence = new int[0];
int[] tmpSequence = new int[fullSequence.length];
int tmpSequenceLength = 0;
for (int i=0;i<fullSequence.length;i++) {
if (i==0 || fullSequence[i] >= fullSequence[i-1]) {
tmpSequence[tmpSequenceLength] = fullSequence[i];
tmpSequenceLength++;
} else {
if (tmpSequenceLength>maxSequence.length) {
maxSequence = new int[tmpSequenceLength];
System.arraycopy(tmpSequence,0,maxSequence,0,maxSequence.length);
}
tmpSequence[0] = fullSequence[i];
tmpSequenceLength=1;
}
}
return maxSequence;
}
https://stackoverflow.com/questions/45442983
复制相似问题