Java中如何对HashMap列表计算用户失败时长?
高效计算用户失败时长的解决方案
核心思路
- 按用户分组:将所有记录按用户名归类,便于单独处理每个用户的状态变化。
- 按时间升序排序:对每个用户的记录按年份从小到大排序,确保能按时间顺序追踪失败到成功的状态转换。
- 遍历计算时长:维护一个变量记录失败状态的起始年份,遇到成功时计算持续时长并累加;若遍历结束后仍处于失败状态,则计算到2022年的时长。
代码实现(Python)
records = [ {"name":"john", "date":2015, "status":"success"}, {"name":"john", "date":2013, "status":"fail"}, {"name":"chris", "date":2013, "status":"success"}, {"name":"john", "date":2012, "status":"fail"}, {"name":"john", "date":2009, "status":"success"}, {"name":"chris", "date":2007, "status":"fail"}, {"name":"john", "date":2005, "status":"fail"}, ] from collections import defaultdict # 1. 按用户分组 user_groups = defaultdict(list) for record in records: user_groups[record["name"]].append(record) # 2. 计算每个用户的总失败时长 failure_duration = {} for username, user_records in user_groups.items(): # 按日期升序排序记录 sorted_records = sorted(user_records, key=lambda x: x["date"]) total = 0 fail_start_year = None for rec in sorted_records: if rec["status"] == "fail": # 标记失败起始年份(仅当当前无活跃失败状态时) if fail_start_year is None: fail_start_year = rec["date"] else: # 遇到成功状态,计算并累加失败时长 if fail_start_year is not None: total += rec["date"] - fail_start_year fail_start_year = None # 处理截止2022年仍处于失败状态的情况 if fail_start_year is not None: total += 2022 - fail_start_year failure_duration[username] = total print(failure_duration) # 输出结果:{'john': 7, 'chris': 6}
方案优势
- 时间效率高:分组操作是O(n)线性时间,每个用户的排序是O(k log k)(k为该用户的记录数),整体复杂度接近O(n),适合处理大规模数据。
- 逻辑清晰:通过状态追踪的方式,准确处理连续失败、失败转成功等多种场景,同时覆盖了截止2022年仍未恢复成功的边界情况。
内容的提问来源于stack exchange,提问作者Good Panic
相关产品推荐
相关产品推荐

