In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element.
public class DuplicateElement {
public static void main(String[] args) {
//Initialize example array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}}}}
OR
int[] array = {1,1,2,3,4,5,6,7,8,8};
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < array.length ; i++)
{
//If same integer is already present then add method will return FALSE
if(set.add(array[i]) == false)
{
System.out.println("Duplicate element found : " + array[i]);
}
}
public class DuplicateElement {
public static void main(String[] args) {
//Initialize example array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}}}}
OR
int[] array = {1,1,2,3,4,5,6,7,8,8};
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < array.length ; i++)
{
//If same integer is already present then add method will return FALSE
if(set.add(array[i]) == false)
{
System.out.println("Duplicate element found : " + array[i]);
}
}
No comments:
Post a Comment