The following method should returns the length of the longest sorted sequence within a list of integers. For example, if a variable called list stores the following sequence of values: {11,12,30,41,5,3,7,6}, it should return 4.
When the longest sorted sequence starts at front, this method fails the test(it returns 3), but it works for the other tests. Does anybody know where the problem is? Thank you.
public int longestSortedSequence() {
int count = 0;
int max1 = 0;
int max2 = 0;
for (int i = 0; i < size; i++) {
if (elementData[i] <= elementData[i + 1]) {
count++;
if (count >= max1) {
max1 = count;
}
} else if (elementData[i] > elementData[i + 1]) {
count = 0;
count++;
if (count >= max2) {
max2 = count;
}
}
}
return Math.max(max1, max2);
}
-
2Why is this marked both Java and C# ?Marek Sebera– Marek Sebera2013年02月24日 23:30:57 +00:00Commented Feb 24, 2013 at 23:30
-
How is elementData declared? What does this have to do with ArrayList?Hot Licks– Hot Licks2013年02月24日 23:32:58 +00:00Commented Feb 24, 2013 at 23:32
-
4What's the point of taking the max between max and max?Hot Licks– Hot Licks2013年02月24日 23:35:59 +00:00Commented Feb 24, 2013 at 23:35
-
2If you have 4 elements in order you will have element N compare smaller than element N+1 3 times.Hot Licks– Hot Licks2013年02月24日 23:37:24 +00:00Commented Feb 24, 2013 at 23:37
-
1count >= max can probably be count > maxChetter Hummin– Chetter Hummin2013年02月24日 23:37:26 +00:00Commented Feb 24, 2013 at 23:37
2 Answers 2
Two comments:
For each
i, you are testing whether elementi+1continues the current non-decreasing sequence. So, before the first iteration of your loop, you should already have counted element 0 as belonging to the current non-decreasing sequence; on the first iteration, you test if element 1 continues that sequence. That meanscountshould be set to 1 in the beginning.Your code will probably throw an ArrayIndexOutOfBoundsException on the last iteration of the for loop, because
i+1will equal size, which is not a valid index into your array.
Comments
I guess the codes in your question were with a lot of copy-paste. e.g. the
if (count>=max)parts.Your codes may throw
IndexOutOfBoundExcep.because you reade[i+1]in your loop, and set with conditioni<sizeThe
countshould be at least 1. (descending sort case), if the array is not empty. When empty array, return 0.
I just did some fixes, and re-wrote a bit. (without writing in IDE, not tested either). Just show some idea.
public int longestSortedSequence() {
if (size==0)return 0; //empty array
int count = 1; //at least 1
int max = 1;
for (int i = 0; i < size-1; i++) {
if (elementData[i] <= elementData[i + 1]) {
count++;
} else {
max=count>max?count:max;
count = 1;
}
}
return count>max? count: max;
}