[英]For loop not continuing as expected in Java?
我正在嘗試編寫代碼來反轉同一數組中 Java 中遞增的子數組(未創建新數組)。 例如,數組items {2, 3, 4, 2, 1, 2, 3, 7, 8}
的輸入應為 output {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}```
您正在回顧比較items[i]
和items[i-1]
。 但是,當它在最后一個索引處結束時,如何找到最后一個遞增序列的結尾呢? 那導致了錯誤。
可能用if (i.= items.length - 1 && items[i] > items[i-1])
解決了。
另外 then-part if (items[i] > items[i-1])
可以被消除,只是在序列結束時響應 (items[i] <= items[i-1]`。
純粹編碼這個邏輯:
i
確定序列的開始和結束結果是:
public static void reverse(int[] items) {
for (int i = 0; i < items.length; ++i) {
int start = i;
int end = i;
while (end + 1 < items.length && items[end + 1] > items[end]) {
++end;
}
i = end;
while (start < end) {
int temp = items[start];
items[start] = items[end];
items[end] = temp;
++start;
--end;
}
}
}
通過在 for 循環之前保留 state 個變量,可以while
確定子序列時消除第一個,但以上是最簡單的。
代碼行數從 17 LoC 減少到 12 LoC。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.