【问题标题】:How can I make my array return in reversed order? [duplicate]如何让我的数组以相反的顺序返回? [复制]
【发布时间】:2021-03-20 13:26:51
【问题描述】:

我需要做的是在方法之前的 cmets 中。 A 包含一个用户输入的 10 元素长数组:

//Reverses the contents of the array. The array remains unchanged
    //It prints the reversed array to the screen
    static void reverseArray(int [] A)
    {
        int[] tempArray = new int[10];

      for(int i = A.length-1; i >= 0; i--)
      {
        //Supposed to copy what's in reversed array A to tempArray
        tempArray[i] = A[i];
      }
        printArray(tempArray); //Prints the updated array to the screen
    }

我想要它做的是从 A 的最后一个元素倒数到第一个元素,然后将其复制到 tempArray。但现在它只打印用户输入的数组。我知道我需要 2 个整数来跟踪增加和减少的内容,但我不知道如何实现它们。

【问题讨论】:

  • 想想吧。输入数组的索引0 处的项目必须位于输出数组的last 索引(此处为索引9)。然后继续以下索引。
  • ArrayUtils.reverse(int[] 数组)

标签: java arrays reverse


【解决方案1】:

这是我的方法

    static void reverseArray(int [] A){
        int[] tempArray = new int[A.length];
        for(int i = 0; i < A.length; i++){
             tempArray[i] = A[A.length - i - 1];
        }
        printArray(tempArray); //Prints the updated array to the screen
    }

    static void printArray(int[] array){
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
    }

【讨论】:

    【解决方案2】:

    所以我看到了this answer,它真的很有帮助。我也可以使用我原来的使用 for 循环的计划,但是 while 循环也很有效。前者可能更容易,因为我不需要做更多的变量,但没关系。

    static void reverseArray(int [] A)
        {
          int i = A.length - 1;
          int j = 0;
          int[] tempArray = new int[A.length];
    
          while(i >= 0)
          {
            tempArray[j] = A[i];
            i--;
            j++;
          }
            printArray(tempArray); //Prints the updated array to the screen
        }
    

    【讨论】:

      【解决方案3】:

      首先,不要硬编码tempArray 的长度。使用A的长度:

      int[] tempArray = new int[A.length];
      

      其次,将A的每个元素复制到tempArray的逆索引中:

      for(int i = A.length-1; i >= 0; i--) {
        tempArray[A.length-1-i] = A[i];
      }
      

      【讨论】:

      • 首先,寻找合适的重复项?
      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多