|
| 1 | +/** |
| 2 | + * 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period |
| 3 | + * https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their |
| 7 | + * key-card, the security system saves the worker's name and the time when it was used. The system |
| 8 | + * emits an alert if any worker uses the key-card three or more times in a one-hour period. |
| 9 | + * |
| 10 | + * You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds |
| 11 | + * to a person's name and the time when their key-card was used in a single day. |
| 12 | + * |
| 13 | + * Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49". |
| 14 | + * |
| 15 | + * Return a list of unique worker names who received an alert for frequent keycard use. Sort the |
| 16 | + * names in ascending order alphabetically. |
| 17 | + * |
| 18 | + * Notice that "10:00" - "11:00" is considered to be within a one-hour period, while |
| 19 | + * "22:51" - "23:52" is not considered to be within a one-hour period. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string[]} keyName |
| 24 | + * @param {string[]} keyTime |
| 25 | + * @return {string[]} |
| 26 | + */ |
| 27 | +var alertNames = function(keyName, keyTime) { |
| 28 | + const usageMap = new Map(); |
| 29 | + for (let i = 0; i < keyName.length; i++) { |
| 30 | + if (!usageMap.has(keyName[i])) { |
| 31 | + usageMap.set(keyName[i], []); |
| 32 | + } |
| 33 | + usageMap.get(keyName[i]).push(timeToMinutes(keyTime[i])); |
| 34 | + } |
| 35 | + |
| 36 | + const result = []; |
| 37 | + for (const [name, times] of usageMap) { |
| 38 | + times.sort((a, b) => a - b); |
| 39 | + for (let i = 2; i < times.length; i++) { |
| 40 | + if (times[i] - times[i - 2] <= 60) { |
| 41 | + result.push(name); |
| 42 | + break; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return result.sort(); |
| 48 | + |
| 49 | + function timeToMinutes(time) { |
| 50 | + const [hours, minutes] = time.split(':').map(Number); |
| 51 | + return hours * 60 + minutes; |
| 52 | + } |
| 53 | +}; |
0 commit comments