for explanation watch video
Find Duplicates using HashSet
import java.util.HashSet;
public class FindDuplicates {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 2, 6, 4, 7, 8, 3};
findDuplicates(array);
}
public static void findDuplicates(int[] array) {
HashSet<Integer> set = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int num : array) {
if (!set.add(num)) { // if add() returns false, num is a duplicate
duplicates.add(num);
}
}
if (duplicates.isEmpty()) {
System.out.println("No duplicates found");
} else {
System.out.println("Duplicate elements: " + duplicates);
}
}
}
Using For loop
public class FindDuplicatesUsingLoop {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 2, 6, 4, 7, 8, 3};
findDuplicates(array);
}
public static void findDuplicates(int[] array) {
boolean hasDuplicates = false;
System.out.print("Duplicate elements: ");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
System.out.print(array[i] + " ");
hasDuplicates = true;
break; // Avoids printing the same duplicate multiple times
}
}
}
if (!hasDuplicates) {
System.out.print("No duplicates found");
}
}
}
Top comments (0)