我试图在Java中反转一个int数组。

此方法不反转数组。

for(int i = 0; i < validData.length; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

有什么问题吗?


当前回答

它有两个解

Loop Recursion public class _1_ReverseArray { public static void main(String[] args) { int array[] = {2, 3, 1, 4, 9}; //reverseArray(array, 0, array.length - 1); reverseArrayWhileLoop(array, 0, array.length - 1); printArray(array); } private static void printArray(int[] array) { for (int a : array) { System.out.println(a); } } private static void reverseArray(int[] array, int start, int end) { if (start > end) { return; } else { int temp; temp = array[start]; array[start] = array[end]; array[end] = temp; reverseArray(array, start + 1, end - 1); } } private static void reverseArrayWhileLoop(int[] array, int start, int end) { while (start < end) { int temp; temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } } }

其他回答

最有效的方法是向后迭代数组。

我不确定Aaron的解决方案是否调用Collections.reverse(list);有人知道吗?

int[] arrTwo = {5, 8, 18, 6, 20, 50, 6};

    for (int i = arrTwo.length-1; i > 0; i--)
    {
        System.out.print(arrTwo[i] + " ");
    }

只是为了它。人们通常只需要反向排列的数组或列表上的“视图”,而不是在处理流和集合时完全不需要反向数组,而是原始数组/集合上的“反向”视图。,最好创建一个在列表/数组上具有反向视图的工具包。

所以创建你的Iterator实现,它接受一个数组或列表并提供输入。

/// Reverse Iterator
public class ReverseIterator<T> implements Iterator<T> {
  private int index;
  private final List<T> list;
  public ReverseIterator(List<T> list) {
     this.list = list;
     this.index = list.size() - 1;
  }
  public boolean hasNext() {
    return index >= 0 ? true : false;
  }
  public T next() {
    if(index >= 0) 
      return list.get(index--);
    else 
      throw new NoSuchElementException();
  }
}

数组情况的实现非常类似。当然,迭代器也可以是流或集合的源。

因此,当你想做的只是迭代数组/列表或将其提供给流或新的集合/数组时,创建一个新数组并不总是最好的。

2种反转数组的方法。

Using For loop and swap the elements till the mid point with time complexity of O(n/2). private static void reverseArray() { int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; for (int i = 0; i < array.length / 2; i++) { int temp = array[i]; int index = array.length - i - 1; array[i] = array[index]; array[index] = temp; } System.out.println(Arrays.toString(array)); } Using built in function (Collections.reverse()) private static void reverseArrayUsingBuiltInFun() { int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; Collections.reverse(Ints.asList(array)); System.out.println(Arrays.toString(array)); } Output : [6, 5, 4, 3, 2, 1]

您的程序只适用于length = 0,1。 你可以试试:

int i = 0, j = validData.length-1 ; 
while(i < j)
{
     swap(validData, i++, j--);  // code for swap not shown, but easy enough
}