有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 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确定序列的开始和结束
    • 反转[开始..结束]

    结果:

    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循环之前保存状态变量,可以消除确定子序列的第一个while,但是上面的方法最简单

    代码行数从17行减少到12行