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
你們寫的都好厲害 :(