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 C++ from the credited upstream file 1604.cpp.
- 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:3 vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) {4 vector<string> ans;5 unordered_map<string, vector<int>> nameToMinutes;6 7 for (int i = 0; i < keyName.size(); ++i) {8 const int minutes = getMinutes(keyTime[i]);9 nameToMinutes[keyName[i]].push_back(minutes);10 }11 12 for (auto& [name, minutes] : nameToMinutes)13 if (hasAlert(minutes))14 ans.push_back(name);15 16 ranges::sort(ans);17 return ans;18 }19 20 private:21 22 23 bool hasAlert(vector<int>& minutes) {24 if (minutes.size() > 70)25 return true;26 ranges::sort(minutes);27 for (int i = 2; i < minutes.size(); ++i)28 if (minutes[i - 2] + 60 >= minutes[i])29 return true;30 return false;31 }32 33 int getMinutes(const string& time) {34 const int h = stoi(time.substr(0, 2));35 const int m = stoi(time.substr(3));36 return 60 * h + m;37 }38};39