Skip to content

Conversation

@ErdemT09
Copy link
Collaborator

We can actually use the constraints given in the question to store the existence of numbers in a boolean array. The array is looped once again and we check if number+1 is true in the array. I personally do not really like this solution as it wouldn't be valid if the constraints were something unknown to us and not limited by LeetCode or the programming language itself (For example, Integer type in Haskell represents an unbounded integer value).
The other solution is a bit more general, and can be pretty fast as well depending on the implementation of the HashSet. We add all the numbers in the array to a set and after that, check if the sought value is in the set.

@altay9
Copy link
Collaborator

altay9 commented May 15, 2021

issue: #150

Comment on lines +4 to +17
public int countElements(int[] arr) {
boolean[] check = new boolean[1002];
int count = 0;
for (int n : arr) {
check[n] = true;
}
for (int n : arr) {
if (check[n + 1]) {
count++;
}
}
return count;
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is quite fine.
image

Comment on lines +7 to +20
public int countElements(int[] arr) {

Set<Integer> nums = new HashSet<>();
int count = 0;
for (int n : arr) {
nums.add(n);
}
for (int n : arr) {
if (nums.contains(n + 1)) {
count++;
}
}
return count;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is quite fine as well.
image

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does the current solution with sorting perform?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Copy link
Collaborator

@altay9 altay9 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for these nice solutions Erdem.

@ErdemT09 ErdemT09 merged commit 983f5fd into master May 15, 2021
@ErdemT09 ErdemT09 deleted the 1426.-Counting-Elements-Linear branch May 15, 2021 18:05
@ErdemT09 ErdemT09 mentioned this pull request May 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants