Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/09/18 14:49), 編輯推噓2(206)
留言8則, 3人參與, 1年前最新討論串875/1548 (看更多)
179. Largest Number ## 思路 sorting 寫個compare function比較數字字串 (A+B , B+A) 然後有個corner case [0, 0, 0] -> '0' ## Code ```python from functools import cmp_to_key class Solution: def largestNumber(self, nums: List[int]) -> str: nums = list(map(str, nums)) def compare(a, b): if a + b > b + a: return 1 if a + b < b + a: return -1 return 0 nums.sort(key=cmp_to_key(compare), reverse=True) if nums[0] == '0': return '0' return ''.join(nums) ``` -- https://i.imgur.com/kyBhy6o.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.48 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1726642178.A.20D.html

09/18 14:50, 1年前 , 1F
今天是這題喔 我前陣子才寫到
09/18 14:50, 1F

09/18 14:50, 1年前 , 2F
誰想得到==
09/18 14:50, 2F

09/18 14:51, 1年前 , 3F
解答的寫法是用lambda x: x*10 這我也想不到..
09/18 14:51, 3F

09/18 14:54, 1年前 , 4F
cmp_to_key又是啥 剩我手做了:(
09/18 14:54, 4F

09/18 14:59, 1年前 , 5F
就sort的cmp在Python3被拿掉了 要用cmp_to_key包回來
09/18 14:59, 5F

09/18 15:00, 1年前 , 6F
我連cmp都不知道是啥了 :(
09/18 15:00, 6F

09/18 15:01, 1年前 , 7F
compare喔
09/18 15:01, 7F

09/18 15:05, 1年前 , 8F
4
09/18 15:05, 8F
文章代碼(AID): #1cwdW28D (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cwdW28D (Marginalman)