Alert Using Same Key-Card Three or More Times in a One Hour Period LeetCode solution in Java

1
class Solution {
2
public List<String> alertNames(String[] keyName, String[] keyTime) {
3
Map<String, PriorityQueue<Integer>> map = new HashMap<>();
4
// for every entry in keyName and keyTime, add that time to a priorityqueue for that name
5
for (int i = 0; i < keyName.length; i++) {
6
PriorityQueue<Integer> pq = map.getOrDefault(keyName[i], new PriorityQueue<Integer>());
7
// convert the time to an integer (0- 2359 inclusive) for easy comparisons
8
pq.add(
9
Integer.parseInt(keyTime[i].substring(0, 2)) * 100
10
+ Integer.parseInt(keyTime[i].substring(3)));
11
map.put(keyName[i], pq);
12
}
13

14
// Generate the "answer" list
15
List<String> ans = new ArrayList<>();
16
for (String s : map.keySet()) {
17
// For each name in the map, determine if that name used the keycard within 1 hour
18
PriorityQueue<Integer> pq = map.get(s);
19
if (active(pq)) {
20
ans.add(s);
21
}
22
}
23

24
// Sort the names alphabetically
25
Collections.sort(ans);
26
return ans;
27
}
28

29
// Greedy function to determine if there were 3 uses within an hour
30
private boolean active(PriorityQueue<Integer> pq) {
31
// If there are two or less entries, the user could not have entered 3 times, return false
32
if (pq.size() < 3) return false;
33

34
// Create rolling data
35
// Using PriorityQueues, the lowest number is removed first by default
36
int a = pq.poll();
37
int b = pq.poll();
38
int c = pq.poll();
39

40
// Test if two entrances are within 1 hour (100 in integer)
41
if (c - a <= 100) return true;
42
while (pq.size() > 0) {
43
a = b;
44
b = c;
45
c = pq.poll();
46
if (c - a <= 100) return true;
47
}
48

49
// If the full Queue has been checked, return false
50
return false;
51
}
52
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0