Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (caster )時間1年前 (2024/05/04 10:45), 編輯推噓6(606)
留言12則, 7人參與, 1年前最新討論串183/1548 (看更多)
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 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.137.123 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1714790731.A.EAE.html

05/04 10:45, 1年前 , 1F
可以不用排序
05/04 10:45, 1F

05/04 10:46, 1年前 , 2F
別卷了
05/04 10:46, 2F

05/04 10:46, 1年前 , 3F
要吧?
05/04 10:46, 3F

05/04 10:46, 1年前 , 4F
別卷了
05/04 10:46, 4F

05/04 10:47, 1年前 , 5F
你用一個array 長度limit+1去記錄每個重量出現的次數
05/04 10:47, 5F

05/04 10:47, 1年前 , 6F
接著一樣是two pointer
05/04 10:47, 6F

05/04 10:48, 1年前 , 7F
你好強
05/04 10:48, 7F

05/04 10:48, 1年前 , 8F
R對欸 這樣就降到O(n)
05/04 10:48, 8F

05/04 10:52, 1年前 , 9F
大師 別卷了
05/04 10:52, 9F

05/04 10:54, 1年前 , 10F
大師...
05/04 10:54, 10F

05/04 10:58, 1年前 , 11F
大師
05/04 10:58, 11F

05/04 10:58, 1年前 , 12F
大師
05/04 10:58, 12F
文章代碼(AID): #1cDQ5Bwk (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cDQ5Bwk (Marginalman)