Re: [闲聊] 每日leetcode

楼主: JerryChungYC (JerryChung)   2024-09-05 10:06:23
https://leetcode.com/problems/find-missing-observations
2028. Find Missing Observations
※ 引述《sustainer123 (caster )》之铭言:
: ※ 引述《DJYOMIYAHINA (通通打死)》之铭言:
: : 有一大坨比我快十倍的不知道怎么用的==
: : 但我看答案都差不多ㄚ
: : 还是有改测资
: : def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
: : m = len(rolls)
: : summation = mean*(n+m)
: : sum_n = summation - sum(rolls)
: : if sum_n<n or sum_n>6*n:
: : return []
: : res = sum_n-(sum_n//n)*n
: : ans = [(sum_n//n)+1] * res + [(sum_n//n)] * (n-res)
: : return ans
: 思路:
: 先求(n+m)总和跟m总和的差值
: 然后 求n的平均 余数后面慢慢加上去
: 另外 里面的元素限定1-6 所以就加个if判断
: Python Code:
: class Solution:
: def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
: diff = mean * (len(rolls) + n) - sum(rolls)
: diff_avg = diff // n
: space = (6 - diff_avg) * n
: remainder = diff % n
: result = []
: if diff < n or diff > 6 * n or remainder > space:
: return result
: for _ in range(n):
: if remainder > 6 - diff_avg:
: remainder -= 6 - diff_avg
: result.append(6)
: else:
: result.append(diff_avg + remainder)
: remainder = 0
: return result
: 写得狗干丑 我就这样了
思路:差不多
先算出差多少数
如果在 n 跟 6n 之外就回传 []
再算平均与余数 看几个余数就加几个
Python Code:
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
lose = mean * (len(rolls) + n) - sum(rolls)
if 1 * n > lose or lose > 6 * n: return []
avg, remainder = divmod(lose, n)
return [avg] * (n - remainder) + [avg+1] * remainder
你们写的都好厉害 :(
楼主: JerryChungYC (JerryChung)   2024-09-05 10:41:00
O(n) / O(n) 好像没更好的解法了 GPT说的leetcode怎么说空间是 O(1)

Links booklink

Contact Us: admin [ a t ] ucptt.com