gpt4 book ai didi

java - 如果发现重复项,则替换数组中的数字

转载 作者:行者123 更新时间:2023-12-01 14:08:35 25 4
gpt4 key购买 nike

让用户在main方法的数组中输入5个整数值。将数组传递到单独的函数中。在那里,检查数组中是否有重复的值。如果发现重复,则消除重复的整数并将其替换为-1。在 main 方法中打印处理后的数组。我想我知道如何用 -1 替换该值,但是如何将数组再次返回到 main 方法。代码是:

 package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}

}
}

最佳答案

使用集合来跟踪您已有的号码。迭代数组并检查该集合是否包含当前位置的数字。如果是:将其替换为-1。如果否:将数字添加到集合中...

public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();

for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}

关于java - 如果发现重复项,则替换数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18714797/

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