Input: Integer array with 0 or more repeated values.
Output: Total number of duplicate numbers present in the given array
The use of Hash set can be done in order to solve this by traversing each element and adding it into the set, later on they are checked for repetitive addition (i.e. we make sure that the numbers were not included already!)
Step 1: Create 2 hash sets. 1 is for all the elements and the other is for the duplicate elements.
Step 2: Loop over each element in the given array
Now, for each element:
a. Check whether the element is in the Hash set
b. If yes, then add it to duplicate set
c. If no, then add it to normal hash set
Step 3: output the size of duplicate hash set
Below is the code in java for the above problem.
You can have below code from GIT.
https://github.com/Niravkumar-Patel/SnippetExampleRepo.git
Below is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.HashSet; public class CountDuplicates { static int countDuplicates(int[] numbers) { HashSet<Integer> set = new HashSet<Integer>(); HashSet<Integer> duplicateSet = new HashSet<Integer>(); for(int i=0;i<numbers.length;i++){ if(set.contains(numbers[i])){ duplicateSet.add(numbers[i]); }else{ set.add(numbers[i]); } } return duplicateSet.size(); } public static void main(String p[]){ int a[]={20,20,20,30,40,50,60,90,80,90,100}; System.out.println("Total Number having duplicate Count:"+countDuplicates(a)); } } |
The output of the above code:
1 2 3 4 5 |
Input: {20,20,20,30,40,50,60,90,80,90,100}; Output: Total Number having duplicate Count:2 |
You can have above code from GIT.