We are working on a security system for a badged-access room in our company’s building.
Given an ordered list of employees who used their badge to enter or exit the room, write a function that returns two collections:
- All employees who didn’t use their badge while exiting the room — they recorded an enter without a matching exit. (All employees are required to leave the room before the log ends.)
- All employees who didn’t use their badge while entering the room — they recorded an exit without a matching enter. (The room is empty when the log begins.)
Each collection should contain no duplicates, regardless of how many times a given employee matches the criteria for belonging to it.
For example:
records = [["Paul", "enter"],
["Pauline", "exit"],
["Paul", "enter"],
["Paul", "exit"],
["Martha", "exit"],
["Joe", "enter"],
["Martha", "enter"],
["Steve", "enter"],
["Martha", "exit"],
["Jennifer", "enter"],
["Joe", "enter"],
["Curtis", "exit"],
["Curtis", "enter"],
["Joe", "exit"],
["Martha", "enter"],
["Martha", "exit"],
["Jennifer", "exit"],
["Joe", "enter"],
["Joe", "enter"],
["Martha", "exit"],
["Joe", "exit"]
]
这道题本质上是对有序门禁日志做一次线性扫描,并用集合或计数表跟踪每个员工当前是否“在房间内”。当某人出现 enter 但之前不在房间里,或出现 exit 但之前已不在房间里,就分别记入两个结果集合:一个表示缺少正确的 exit,另一个表示缺少正确的 enter。因为要求去重,所以结果最好用 set 保存,最后再转换为列表输出。该题重点在于正确处理同一员工多次进出、日志顺序依赖,以及“房间初始为空”和“日志结束前必须离开”的约束。