Showing posts with label find-duplicate-no-in-array. Show all posts
Showing posts with label find-duplicate-no-in-array. Show all posts

Tuesday, August 21, 2018

How to find duplicate elements in an array using HashSet?



package com.altafjava.fdeia.test;

import java.util.HashSet;

public class Test2 {

public static void main(String[] args) {
int[] arr={1,6,5,1,2,2,9,6};
System.out.println("Input Array = 1,6,5,1,2,2,9,6");
        System.out.print("The repeating elements are : ");
        HashSet<Integer> hashSet=new HashSet<>();
        for (int i = 0; i < arr.length; i++)
        {
        if(hashSet.add(arr[i])==false)
        System.out.print(arr[i]+" ");
        }       
}
}


As we know HashSet does not allow duplicate elements. We can get benifit from it. If we add element into HashSet and if it is returning false. It that means it element is already added HashSet and this is duplicate element.





How to find duplicate elements in an array using HashSet?
How to find duplicate elements in an array using HashSet?






How to find duplicate elements in an array?



package com.altafjava.fdeia.test;

public class Test {

public static void main(String[] args) {
int[] arr={1,6,5,1,2,2,9,6};
System.out.println("Input Array = 1,6,5,1,2,2,9,6");
        System.out.print("The repeating elements are : ");
        for (int i = 0; i < arr.length; i++)
        {
        for(int j=i+1;j<arr.length;j++){
        if(arr[i]==arr[j]){
        System.out.print(arr[i]+" ");
        break;
        }
        }
        }       
}
}


Note:-
We are using Brute Force Mechanism. This will take lot of time. Hence we can take the help of HashSet but in interview they check your logical skill.





How to find duplicate elements in an array?
How to find duplicate elements in an array?