用 Python 编写程序来查找最长不同子列表的长度

pythonserver side programmingprogramming更新于 2026/1/23 21:00:17

假设我们有一个名为 nums 的数字列表,我们必须找到最长的连续子列表的长度,其中所有元素都是唯一的。

因此,如果输入为 nums = [6, 2, 4, 6, 3, 4, 5, 2],则输出将为 5,因为最长的唯一元素列表为 [6, 3, 4, 5, 2]。

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

  • head := 0, dct := a new map

  • max_dist := 0

  • 对于 nums 中的每个索引 i 和元素 num,执行

    • 如果 num 在 dct 中,并且 dct[num] >= head,则

      • head := dct[num] + 1

    • dct[num] := i

    • 如果 i - head + 1 > max_dist,则

      • max_dist := i - head + 1

  • 返回 max_dist

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

示例

class Solution:
   def solve(self, nums):
      head = 0
      dct = {}
      max_dist = 0
      for i, num in enumerate(nums):
         if num in dct and dct[num] >= head:
            head = dct[num] + 1
         dct[num] = i
         if i - head + 1 > max_dist:
            max_dist = i - head + 1
   return max_dist
ob = Solution()
nums = [6, 2, 4, 6, 3, 4, 5, 2]
print(ob.solve(nums))

输入

[6, 2, 4, 6, 3, 4, 5, 2]

输出

5

相关文章


有用资源