Java + Count duplicates from int array without using any Collection or another intermediate Array
The easiest way to solve this problem is to sort the array first, and then just walk through the array counting duplicates as you encounter them:
int[] numbers = new int[]{7,2,6,1,4,7,4,5,4,7,7,3,1};
int temp = 0;
// I chose to do a bubble sort of the array,
// but you are free to use any method you wish (e.g. Arrays.sort)
System.out.print("Duplicates values: ");
for (int i=0; i < numbers.length; ++i) {
for (int j=1; j < (numbers.length - i); ++j) {
if (numbers[j-1] > numbers[j]) {
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
// walk through the sorted array and count duplicates
int numDup = 0, dupCount = 0;
int previous = -1;
for (int i=0; i < numbers.length; ++i) {
if (numbers[i] == previous) {
++numDup;
if (numDup == 1) {
++dupCount;
if (dupCount == 1) {
System.out.print(numbers[i]);
}
else {
System.out.print(", " + numbers[i]);
}
}
}
else {
previous = numbers[i];
numDup = 0;
}
}
System.out.println("\nNumber of duplicates values: " + dupCount);
Output:
Duplicates values: 1, 4, 7
Number of duplicates values: 3
Note that my output order is reverse of what you have, because you need to read through the entire array before you know how many total duplicates you have. Also, I will point out that the only state this solution uses is the input array itself, plus a couple of int
varibles here and there.
This code has been tested in IntelliJ and it works correctly.
Agreed to Tim @tim-biegeleisen. Just minor change. Use the Arrays to sort the array.
import java.util.*;
public class DuplicateClass {
public static void main(String[] args) {
int[] values = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
duplicate(values);
}
public static void duplicate(int numbers[]) {
Arrays.sort(numbers);
int previous = numbers[0] - 1;
int dupCount = 0;
for (int i = 0; i < numbers.length; ++i) {
if (numbers[i] == previous) {
++dupCount;
} else {
previous = numbers[i];
}
}
System.out.println("There were " + dupCount + " duplicates in the array.");
}
}