-
Notifications
You must be signed in to change notification settings - Fork 16
/
ArrayOfAges.java
34 lines (30 loc) · 943 Bytes
/
ArrayOfAges.java
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
package by.andd3dfx.sorting;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* We have a very long array of people ages.
* Need to count number of people for each age.
*
* @see <a href="https://youtu.be/vFsDPm7ecsM">Video solution</a>
*/
public class ArrayOfAges {
/**
* We use the "bucket sorting" approach to collect statistics,
* because ages belong to definite range [0-130].
* <p>
* In result, we got O(1) consumption of additional memory.
*/
public static Map<Integer, Long> process(int[] ages) {
long[] buckets = new long[130];
for (var age : ages) {
buckets[age]++;
}
Map<Integer, Long> map = new LinkedHashMap<>();
for (var age = 0; age < buckets.length; age++) {
if (buckets[age] > 0) {
map.put(age, buckets[age]);
}
}
return map;
}
}