- Leetcode 3408. Design Task Manager
- 1. 解题思路
- 2. 代码实现
- 题目链接:3408. Design Task Manager
1. 解题思路
这一题的核心就是怎么去设计这个数据结构使得可以快速实现以下两个功能:
- 快速地找到优先级最高的task
- 如何通过taskid快速找到其对应的userid以及priority信息,并对其进行修改。
前者,我们可以通过一个有序队列对其进行存储和维护,后者,我们只需要对每一个taskid构造一个字典即可。
2. 代码实现
给出python代码实现如下:
class TaskManager:
def __init__(self, tasks: List[List[int]]):
self.tasks = {}
self.queue = []
for userId, taskId, priority in tasks:
self.add(userId, taskId, priority)
return
def add(self, userId: int, taskId: int, priority: int) -> None:
self.tasks[taskId] = (userId, priority)
bisect.insort(self.queue, (priority, taskId, userId))
return
def edit(self, taskId: int, newPriority: int) -> None:
userId, priority = self.tasks[taskId]
self.rmv(taskId)
self.add(userId, taskId, newPriority)
return
def rmv(self, taskId: int) -> None:
userId, priority = self.tasks[taskId]
self.queue.pop(bisect.bisect_left(self.queue, (priority, taskId, userId)))
self.tasks.pop(taskId)
return
def execTop(self) -> int:
if self.queue == []:
return -1
priority, taskId, userId = self.queue.pop()
return userId
# Your TaskManager object will be instantiated and called as such:
# obj = TaskManager(tasks)
# obj.add(userId,taskId,priority)
# obj.edit(taskId,newPriority)
# obj.rmv(taskId)
# param_4 = obj.execTop()
提交代码评测得到:耗时2135ms,占用内存108.4MB。