Python程式:查詢救援所需最小火箭數量


假設我們有一個名為weights的數字列表,它表示人們的體重,還有一個值limit,它決定了一艘火箭的重量限制。現在每艘火箭最多可以搭載兩個人。我們必須找到將所有人營救到星球所需的最少火箭數量。

因此,如果輸入類似於weights = [300, 400, 300],limit = 600,則輸出將為2,因為將需要一艘火箭搭載兩個體重為300的人,另一艘搭載體重為400的人。

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

  • 對列表weights進行排序

  • cnt := 0

  • 當weights非空時,執行以下操作:

    • x := 從weights中刪除最後一個元素

    • 如果weights非空且weights[0] <= limit − x,則執行以下操作:

      • 從weights中刪除第一個元素

    • cnt := cnt + 1

  • 返回cnt

讓我們看看以下實現,以便更好地理解:

示例(Python)

 線上演示

class Solution:
def solve(self, weights, limit):
   weights.sort()
   cnt = 0
   while weights:
      x = weights.pop()
      if weights and weights[0] <= limit - x:
         weights.pop(0)
      cnt += 1
   return cnt
ob = Solution()
weights = [300, 400, 300]
limit = 600
print(ob.solve(weights, limit))

輸入

[300, 400, 300], 600

輸出

2

更新於: 2020年10月21日

141 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.