Count Distinct Elements
Problem
Print how many different values the array has.
Constraints
- 1 <= n <= 10^5
Examples
Input
6 4 1 4 2 1 3
Output
4
Solutions
A set stores each value once, so its size is the count of distinct values.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The number of different values.
* Approach: Use a set.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a) {
// Step 1: A HashSet keeps only different values.
java.util.Set<Integer> unique = new java.util.HashSet<>();
for (int value : a) {
unique.add(value);
}
// Step 2: The size of the set is the answer.
return unique.size();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- What does a set do with a repeated value?