【发布时间】:2014-12-03 23:01:12
【问题描述】:
问题 H(最长自然后继):
如果第二个整数是自然数序列中第一个整数的后继(1 和 2 是自然后继),则两个连续整数是自然后继。编写一个程序,读取一个数字 N 后跟 N 个整数,然后打印最长的连续自然后继序列的长度。
例子:
输入 7 2 3 5 6 7 9 10 输出 3 这是我目前的代码,我不知道为什么它不起作用
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int[] array = new int[x];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
System.out.println(array(array));
}
public static int array(int[] array) {
int count = 0, temp = 0;
for (int i = 0; i < array.length; i++) {
count = 0;
for (int j = i, k = i + 1; j < array.length - 1; j++, k++) {
if (Math.abs(array[j] - array[k]) == 1) {
count++;
} else {
if (temp <= count) {
temp = count;
}
break;
}
}
}
return temp + 1;
}
}
【问题讨论】:
-
5 6 7 = 3?不是正确答案?
-
@KevH 是的,这个答案是正确的,但我的程序没有返回它