-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCountingElements.java
More file actions
41 lines (33 loc) · 880 Bytes
/
CountingElements.java
File metadata and controls
41 lines (33 loc) · 880 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package array;
import java.util.HashSet;
import java.util.Set;
/**
* Description: https://leetcode.com/problems/counting-elements
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class CountingElements {
public int countElementsViaSet(int[] arr) {
Set<Integer> seen = new HashSet<>();
for (int num : arr) {
seen.add(num);
}
int count = 0;
for (int num : arr) {
if (seen.contains(num + 1)) count++;
}
return count;
}
public int countElementsViaFreqMap(int[] arr) {
int[] freqMap = new int[1001];
for (int num : arr) {
freqMap[num]++;
}
int count = 0;
for (int i = 0; i < freqMap.length - 1; i++) {
if (freqMap[i + 1] > 0) count += freqMap[i];
}
return count;
}
}