gpt4 book ai didi

java - 在 Java 中使用交换来反转数组

转载 作者:行者123 更新时间:2023-12-01 09:20:16 24 4
gpt4 key购买 nike

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

I just want to clarify that I know how to reverse an array but I would rather appreciate help if any for this particular solution of mine. So please don't mark it as a duplicate.

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;
}

}

我已经根据评论中提供的链接更改了我的解决方案。我在某些测试用例中一切正常,但在某些测试用例中,代码失败了。我认为我已经正确完成了。因此,任何帮助将不胜感激。谢谢

最佳答案

感谢 conscells、ajb 和 Amadan 引导我找到解决此问题的正确位置

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

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;
}
}

关于java - 在 Java 中使用交换来反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40210316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com