gpt4 book ai didi

java - 如何修复以下问题,使其只能返回数组中不重复的值?

转载 作者:行者123 更新时间:2023-12-01 19:34:51 25 4
gpt4 key购买 nike

我有一个排序的整数数组,其中一些值重复,但我想返回不重复的值。例如,我有这个:

Integer[] arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};

它应该返回值-32700。但是,它的结果是 -32560。

我的方法可能有什么问题?

这是我的代码:

    Integer[] arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};
int n = arr.length;
//to store repeating element
int[] temp = new int[1];

//if only one element return it
if(arr.length==1)
{
System.out.println(arr[0]);
}
else
{
for(int j=1; j<n-1; j++)
{ //compare current element with it's previous and subsequent
if((arr[j-1]!=arr[j]) && (arr[j]!=arr[j+1]))
{
temp[0] = arr[j];
}

}
System.out.println(temp[0]);
}

最佳答案

这里的问题是您正在比较 Integer 对象实例的相等性而不是值。只需获取您的代码,我就会在 IDE 中针对您正在使用的比较发出警告。如果您想与原始值进行比较,最简单的更改是将数组的声明更改为

int[] arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};

这样做将产生预期的结果-32700

如果您想让数组保留 Integer 对象,另一种解决方案是按照 Michael Michailidis 的建议进行操作,并在比较中使用 equals。

关于java - 如何修复以下问题,使其只能返回数组中不重复的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58215557/

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