使用Java交换来反转数组

时间:2016-10-24 03:31:59

标签: java arrays

我知道这个问题已经被其他语言提出过,包括Java本身。

  

我只是想澄清一下,我知道如何反转数组,但我更愿意为我的这个特定解决方案提供帮助。   所以请不要将其标记为重复。

import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
    /*
         Code for User input
    */

    /* The problem was with the Swapping Code below */
    for(int i=0; i<=n/2; i++)
        swap(i,n-i-1,a);

  /* Output Code. */

    }
/*Swap function*/
public static void swap(int x, int y, int[] arr){
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

}

我已经根据评论中提供的链接更改了我的解决方案。我在一些测试用例中没有问题,但在某些情况下,代码失败了。我想我已经正确完成了。所以任何帮助都将受到赞赏。感谢

1 个答案:

答案 0 :(得分:1)

感谢 conscells,ajb和Amadan 带领我找到解决此问题的正确位置

这是在Java中反转数组的正确解决方案。我知道已经为此提供了解决方案,但只是想让这个问题对未来的用户有用。谢谢。

import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int a[] = new int[n];
    for(int i=0; i<n; i++)
        a[i] = scan.nextInt();
    for(int i=0; i<n/2; i++)
        swap(i,n-i-1,a);
    for(int i=0; i<n; i++)
        System.out.println(a[i]);

    }

public static void swap(int x, int y, int[] arr){
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

}