Approach
Sorting and greedy selection
For Alert Using Same Key-Card Three or More Times in a One Hour Period, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 39 lines of Java from the credited upstream file 1604.java.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<String> alertNames(String[] keyName, String[] keyTime) {3 List<String> ans = new ArrayList<>();4 HashMap<String, List<Integer>> nameToMinutes = new HashMap<>();5 6 for (int i = 0; i < keyName.length; i++) {7 final int minutes = getMinutes(keyTime[i]);8 nameToMinutes.putIfAbsent(keyName[i], new ArrayList<>());9 nameToMinutes.get(keyName[i]).add(minutes);10 }11 12 for (Map.Entry<String, List<Integer>> entry : nameToMinutes.entrySet()) {13 final String name = entry.getKey();14 List<Integer> minutes = entry.getValue();15 if (hasAlert(minutes))16 ans.add(name);17 }18 19 Collections.sort(ans);20 return ans;21 }22 23 private boolean hasAlert(List<Integer> minutes) {24 if (minutes.size() > 70)25 return true;26 Collections.sort(minutes);27 for (int i = 2; i < minutes.size(); i++)28 if (minutes.get(i - 2) + 60 >= minutes.get(i))29 return true;30 return false;31 }32 33 private int getMinutes(String time) {34 final int h = Integer.parseInt(time.substring(0, 2));35 final int m = Integer.parseInt(time.substring(3));36 return 60 * h + m;37 }38}39