703291. Positive distinct count
Easy
Positive Distinct Count
Summary
Given an array of integers, this problem requires you to count the number of distinct positive elements in the array. The key concept involved is arrays and data structures.
Detailed Explanation
The problem can be solved by iterating through the array and checking if each element is greater than zero. If it is, we increment a counter for the positive distinct elements. This approach ensures that we only count each positive number once, hence the term "distinct".
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto 0. - Iterate through the array from start to end.
- For each element in the array, check if it is greater than zero.
- If the element is positive, increment the
countvariable. - Return the final value of
count, which represents the number of distinct positive elements.
The time complexity for this solution is O(n), where n is the size of the input array, since we are making a single pass through the array. The space complexity is O(1), as we only use a constant amount of space to store the count variable.
Optimized Solutions
Java
public int positiveDistinctCount(int[] arr) {
Set<Integer> set = new HashSet<>();
int count = 0;
for (int num : arr) {
if (num > 0) {
set.add(num);
}
}
return set.size();
}