-
Notifications
You must be signed in to change notification settings - Fork 7
1426. Counting Elements-Two alternative solutions #206
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
issue: #150 |
| 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; | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| 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; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
altay9
left a comment
There was a problem hiding this 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.



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,
Integertype 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.