用 Python 编写程序,查找在哪个时间间隔内完成了多少任务

pythonserver side programmingprogramming更新于 2026/2/3 21:00:17

假设我们有一个时间间隔列表,其中每个时间间隔都类似于 [start, end),并且我们还有一个称为类型的字符串列表。现在对于给定的 i,intervals[i] 显示某人从 [start, end) 开始处理工作 types[i] 的时间。相同类型的两个时间间隔永远不会重叠或接触。因此,我们必须找到一个排序的合并列表,其中每个项目都有 [start, end, num_types],表示从开始到结束,正在处理的任务数量为 num_types。

因此,如果输入类似于 intervals = [ [0, 3], [5, 7], [0, 7] ] types = ["problem solving", "news","game play"],则输出将是 [[0, 3, 2], [3, 5, 1],[5, 7, 2]],因为我们有以下几种类型的工作:[0, 3) "problem solving" 和 "game play" 之间、[3, 5) "game play" 之间以及 [5, 7) "news" 之间和"游戏玩法"。

为了解决这个问题,我们将遵循以下步骤 −

  • ev := 一个新列表

  • 对于间隔中的每个间隔开始结束对 (s, e),执行

    • 在 ev 末尾插入 (s, 1)

    • 在 ev 末尾插入 (e, −1)

  • 对列表 ev 进行排序

  • cnt := 0, last := −1

  • ans := 一个新列表

  • 对于 ev 中事件的每个时间和增量参数 (t, inc),执行

    • 如果 t 与 last 不同,且 cnt 不等于 0,则

      • cnt := cnt + inc

    • last := t

  • 返回 ans

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, intervals, jobs):
      ev = []
      for s, e in intervals:
         ev.append((s, 1))
         ev.append((e, −1))
      ev.sort()
      cnt = 0
      last = −1
      ans = []
      for t, inc in ev:
         if t != last and cnt != 0:
            ans.append([last, t, cnt])
         cnt += inc
         last = t
      return ans
ob = Solution()
intervals = [
   [0, 3],
   [5, 7],
   [0, 7]
]
types = ["problem solving", "news", "game play"]
print(ob.solve(intervals, types))

输入

[[0, 3],[5, 7],[0, 7]], ["problem solving", "news", "game play"]

输出

[[0, 3, 2], [3, 5, 1], [5, 7, 2]]

相关文章


有用资源