程序在Python中查找大小为k的子列表的最大值

假设我们有一个列表num和另一个值k,我们必须找到大小为k的每个子列表的最大值。

因此,如果输入像nums = [12,7,3,9,10,9] k = 3,那么输出将是[12,9,10,10]

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

  • 如果k> nums的大小,则

    • 返回一个空白列表

  • res:=一个新列表

  • temp:= nums [0]

  • 温度:= npoint:= 0

  • 对于i在0到k − 1的范围内

    • temp:= nums [i]

    • 点:=我

    • 如果nums [i]> temp,则

  • 在res的末尾插入temp

  • 对于范围在k到nums的i

    • temp:= nums [i]

    • 点:=我

    • 点:= i − k + 1

    • 对于范围i − k + 1至i的j,做

    • temp:= nums [point]

    • 点:= j

    • 如果nums [j]> nums [point],则

    • temp:= nums [point]

    • 如果nums [i] <temp和(i-point)<k,则

    • 否则,当nums [i] <temp并且(i-点)> = k时,则

    • 除此以外,

    • 在res的末尾插入temp

    • 返回资源

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

    示例

    class Solution:
       def solve(self, nums, k):
          if k > len(nums):
             return []
          res = []
          temp = nums[0]
          point = 0
          for i in range(k):
             if nums[i] > temp:
                temp = nums[i]
                point = i
          res.append(temp)
          for i in range(k, len(nums)):
             if nums[i] < temp and (i − point) < k:
                temp = nums[point]
             elif nums[i] < temp and (i − point) >= k:
                point = i − k + 1
                for j in range(i − k + 1, i + 1):
                   if nums[j] > nums[point]:
                      point = j
                temp = nums[point]
             else:
                temp = nums[i]
                point = i
             res.append(temp)
          return res
    ob = Solution()
    nums = [12, 7, 3, 9, 10, 9]
    k = 3
    print(ob.solve(nums, k))

    输入值

    [12, 7, 3, 9, 10, 9], 3
    输出结果
    [12, 9, 10, 10]

    猜你喜欢