LeetCode Problems #881
阿新 • • 發佈:2018-12-19
2018年11月4日
881. Boats to Save People
問題描述:
The i
-th person has weight people[i]
, and each boat can carry a maximum weight of limit
.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit
.
Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)
樣例:
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Note:
- 1 <= people.length <= 50000
- 1 <= people[i] <= limit <= 30000
問題分析:
本題難度為Medium
!屬於貪心問題,已給出的函式定義為:
class Solution:
def numRescueBoats(self, people, limit):
"""
:type people: List[int]
:type limit: int
:rtype: int
"""
此題的需求是使船的數量最小,如果最重的人可以與最輕的人共用一艘船,那麼就安排他們坐同一條船。否則,最重的人無法與任何人配對(因為其他人都比最輕的人重),那麼他將自己獨自乘一艘船。
演算法; 首先對people進行從小到大排序。 令 people[light_index] 指向當前最輕的人(即列表前向),而 people[heavy_index] 指向最重的那人(即列表反向)。 如果最重的人可以與最輕的人可以坐同一條船(即 people[light_index] + people[heavy_index] <= limit),則船數量加一,更新最重的人和最輕的人;否則,最重的人自己獨自坐一條船,更新最重的人。最輕的人待定。直到所有人離開。
程式碼實現:
使用雙指標
# coding=utf-8
class Solution:
def numRescueBoats(self, people, limit):
"""
:type people: List[int]
:type limit: int
:rtype: int
"""
people.sort()
light_index, heavy_index = 0, len(people) - 1
num_boat = 0
while light_index <= heavy_index:
num_boat += 1
if people[light_index] + people[heavy_index] <= limit:
light_index += 1
heavy_index -= 1
return num_boat