gpt4 book ai didi

java - 从java中的数组中查找重复元素出现两次以上

转载 作者:行者123 更新时间:2023-11-30 06:03:43 28 4
gpt4 key购买 nike

我想从数组中找出重复元素和索引号。我为此写了一个代码。它运行良好,但仅当重复元素的数量超过 2 时才无法生成准确的输出。我从文件中读取值,然后构建一个数组,然后从该数组中搜索重复元素。

import java.io.File;
import java.util.Arrays;
import java.util.Scanner;

public class T1 {
public static void main(String args[]) throws Exception{
Scanner x=new Scanner(new File("C:\\Duplicate_array.txt"));
int [] duplicate_data=new int[9];
int i1=0;
while(x.hasNext()){
int a=x.nextInt();
duplicate_data[i1]=a;
i1++;
}
System.out.println(Arrays.toString(duplicate_data));
for (int i = 0; i < duplicate_data.length-1; i++) {
for (int j = i+1; j < duplicate_data.length; j++) {
if ((duplicate_data[i] == duplicate_data[j]) && (i != j)) {
System.out.println("Duplicate Element : "+duplicate_data[j]);
System.out.println("Index of that duplicate element : "+j);
}
}
}
}
}

这是我的输出:

[5, 6, 1, 6, 9, 5, 2, 1, 5]
Duplicate Element : 5
Index of that duplicate element : 5
Duplicate Element : 5
Index of that duplicate element : 8
Duplicate Element : 6
Index of that duplicate element : 3
Duplicate Element : 1
Index of that duplicate element : 7
Duplicate Element : 5
Index of that duplicate element : 8

最后一行错误。它已经在第 8 个位置开始找到 5。但是在程序结束时它再次搜索 5 并给出第 5 个位置。最后的搜索是不必要的。如何摆脱最后一次搜索?

最佳答案

(i != j) 在您的 if 语句中不是必需的,因为 j 总是领先于 i 1,但那是不是你的问题。

您可以尝试使用重复数组标志来了解您何时已经找到重复项。

import java.util.Arrays;

public class StackOverflow {
public static void main(String args[]) throws Exception {
int[] duplicate_data = {5,6,1,6,9,5,2,1,5};
boolean[] duplicate = new boolean[duplicate_data.length];

System.out.println(Arrays.toString(duplicate_data));
for (int i = 0; i < duplicate_data.length - 1; i++) {
for (int j = i + 1; j < duplicate_data.length; j++) {
// Make sure you haven't flagged this as a duplicate already
if (!duplicate[j] && duplicate_data[i] == duplicate_data[j]) {
duplicate[j] = true;
System.out.println("Duplicate Element : " + duplicate_data[j]);
System.out.println("Index of that duplicate element : " + j);
}
}
}
}
}

结果:

[5, 6, 1, 6, 9, 5, 2, 1, 5]
Duplicate Element : 5
Index of that duplicate element : 5
Duplicate Element : 5
Index of that duplicate element : 8
Duplicate Element : 6
Index of that duplicate element : 3
Duplicate Element : 1
Index of that duplicate element : 7

关于java - 从java中的数组中查找重复元素出现两次以上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51501295/

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