For循环在Java中没有按预期继续?
我正试图编写一个代码,在同一个数组(没有创建新的数组)中反转Java中增加的子数组。例如,数组items {2, 3, 4, 2, 1, 2, 3, 7, 8}
的输入应该输出{4, 3, 2, 2, 8, 7, 3, 2, 1}
。到目前为止,我的代码正在反转第一个增加的子数组,但是过去的元素似乎没有循环
以下是我目前的代码:
public static void reverse(int[] items)
{
int start = 0;
int count = 0;
for (int i = 1; i < items.length; i++)
{
if (items[i] > items[i-1])
{
if (count < 1)
{
start = i-1;
count ++;
}
else
{
count ++;
}
}
else
{
int j, k;
for (j = start; j < count/2; j++)
{
k = items[j];
items[j] = items[count - j];
items[count - j] = k;
j++;
}
count = 0;
}
}
output:
```{4, 3, 2, 2, 1, 2, 3, 7, 8}```
# 1 楼答案
您正在回过头来比较
items[i]
和items[i-1]
。但是,当最后一个递增序列在最后一个索引处结束时,如何找到它的结尾呢?这导致了错误可能用
if (i != items.length - 1 && items[i] > items[i-1])
解决此外,然后的部分
if (items[i] > items[i-1])
也可以消除,只在序列结束时响应(items[i]<;=items[i-1]`仅对这种逻辑进行编码:
i
确定序列的开始和结束结果:
通过在for循环之前保存状态变量,可以消除确定子序列的第一个
while
,但是上面的方法最简单代码行数从17行减少到12行