Count Distinct Elements
easySave
ArrayCountingHash Table
Given an array of integers, return the count of distinct elements in the array.
Example 1
Input
[ 1, 2, 2, 3, 4, 4, 4 ]
Output
4
Explanation. The distinct elements are 1, 2, 3, and 4.
Example 2
Input
[ 7, 7, 7, 7 ]
Output
1
Explanation. The only distinct element is 7.
Example 3
Input
[ -1, 0, 1, -1, 2, 2 ]
Output
4
Explanation. The distinct elements are -1, 0, 1, and 2.
Example 4
Input
[]
Output
0
Explanation. There are no elements in the empty array, thus no distinct elements.
Follow-up: Can you solve this problem in O(n) time complexity using additional O(n) space?
Constraints:
The input array may contain both positive and negative integers, including zeros.
- Views
- 2