Python 中查詢大小為 k 的子列表的最大值程式


假設我們有一個列表 nums 和另一個值 k,我們需要找到大小為 k 的每個子列表的最大值。

因此,如果輸入類似於 nums = [12, 7, 3, 9, 10, 9] k = 3,則輸出將為 [12, 9, 10, 10]

為了解決這個問題,我們將遵循以下步驟:

  • 如果 k > nums 的大小,則

    • 返回一個空列表

  • res := 一個新列表

  • temp := nums[0]

  • temp := npoint := 0

  • 對於 i 從 0 到 k − 1,執行

    • 如果 nums[i] > temp,則

      • temp := nums[i]

      • point := i

  • 將 temp 插入 res 的末尾

  • 對於 i 從 k 到 nums 的大小,執行

    • 如果 nums[i] < temp 且 (i − point) < k,則

      • temp := nums[point]

    • 否則,當 nums[i] < temp 且 (i − point) >= k 時,則

      • point := i − k + 1

      • 對於 j 從 i − k + 1 到 i,執行

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

          • point := j

      • temp := nums[point]

    • 否則,

      • temp := nums[i]

      • point := i

    • 將 temp 插入 res 的末尾

  • 返回 res

讓我們看看下面的實現,以獲得更好的理解:

示例

 即時演示

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]

更新於: 2020-12-15

134 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告