读取整数序列并在序列按升序或降序排序时输出 true 的程序



我一直在练习中遇到问题,这问我的是这样的:

编写一个程序,该程序读取整数序列,如果序列按顺序排序(升序或降序(,则输出 true,否则输出 false。请记住,如果一个数字与以下数字具有相同的值,则不会破坏顺序。

序列以 0 结尾。不要将此数字视为序列的一部分。序列始终至少有一个数字(不包括 0(。

示例输入 1:

9 8 7 6 5 4 3 2 1 0 示例输出 1:

真 示例输入 2:

1 2 3 3 9 0 示例输出 2:

真 示例输入 3:

1 2 5 5 2 3 0 示例输出 3:

我拥有的代码,为了解决这个问题,我有一个错误。

Scanner sc = new Scanner(System.in);
int as = 0;
int ds = 0;
int eq = 0;
int n = sc.nextInt();
int a;
int num = sc.nextInt();
for(int  i = 1 ;i < n ; i++)
{
a = sc.nextInt();
while(a != 0)
{
if (a < num)                 ////// descending order
{
num = a;
ds = 1;
break;
}
else if ( a == num )                 ////////equal
{
num = a;
eq = 1;
break;
}
else                                        //////////ascending order
{
num = a;
as = 1;
break;
}
}
}
if(ds == 1 && as ==1 && eq==1 )
{
System.out.println("false");
}
else if ( (as == 1 && eq ==1) || ds ==0)
{
System.out.println("true");
}
else if ( (ds ==1 && eq==1) || as ==0)
{
System.out.println("true");
}
}

我已经检查了我的代码,任务在第三次测试中显示失败。该任务显示我的输出为真,而我的输出为假。我已经在显示错误的地方运行了我的代码。为什么会这样?

我的代码有些脏,你会接受一个更简单、更短的方法来解决这个问题,还是告诉我我的错误可能是什么,请非常感谢你的时间和答案

我不确定你的练习有什么限制,但我会做这样的事情。 一次从输入中获取所有值,这样就可以避免可能造成混乱的嵌套循环。然后,如果最后一个元素为 0,则将其删除。最后,将列表的排序版本存储在 2 个单独的列表中,并将原始版本与原始版本进行比较。

Scanner sc = new Scanner(System.in);
List<Integer> sequence = new ArrayList<>();
int n = sc.nextInt();
for(int i = 0; i < n; i++){
sequence.add(sc.nextInt());
}
if(sequence.get(sequence.size() - 1) == 0){
sequence.remove(sequence.size() - 1);
}
List<Integer> ascOrder = new ArrayList<>(sequence);
Collections.sort(ascOrder);
List<Integer> descOrder = new ArrayList<>(sequence);
Collections.sort(descOrder,Collections.reverseOrder());
boolean isOrdered = sequence.equals(ascOrder) || sequence.equals(descOrder);
System.out.println(String.valueOf(isOrdered));

最新更新