Re: [閒聊] 每日leetcode

作者: sustainer123 (caster)   2024-05-04 10:45:28
https://leetcode.com/problems/boats-to-save-people
881. Boats to Save People
給定一陣列people 此陣列代表需要上船的人 people[i]代表此人的體重
你現在有無限艘船 船有承重上限limit 每艘船一次最多載兩個人
請回傳帶回所有人所需的最少船隻數
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)
Constraints:
1 <= people.length <= 5 * 104
1 <= people[i] <= limit <= 3 * 104
思路:
排序然後two pointer
Python Code:
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
boats = 0
light = 0
heavy = len(people) - 1
while light <= heavy:
if people[light] + people[heavy] <= limit:
light += 1
heavy -= 1
boats += 1
return boats
作者: JIWP (JIWP)   2023-05-04 10:45:00
可以不用排序別卷了
作者: sustainer123 (caster)   2024-05-04 10:46:00
要吧?
作者: wu10200512 (廷廷)   2024-05-04 10:46:00
別卷了
作者: JIWP (JIWP)   2024-05-04 10:47:00
你用一個array 長度limit+1去記錄每個重量出現的次數接著一樣是two pointer
作者: wu10200512 (廷廷)   2024-05-04 10:48:00
你好強
作者: sustainer123 (caster)   2024-05-04 10:48:00
R對欸 這樣就降到O(n)
作者: argorok (s.green)   2024-05-04 10:52:00
大師 別卷了
作者: DJYOSHITAKA (Evans)   2024-05-04 10:54:00
大師...
作者: SecondRun (雨夜琴聲)   2024-05-04 10:58:00
大師
作者: digua (地瓜)   2024-05-04 10:58:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com