ZhongKuo0228 / study

0 stars 0 forks source link

1431. Kids With the Greatest Number of Candies #61

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

滿簡單的題目

  1. 找最大值
  2. 看給額外糖果有沒有超過最大值,有則 True
class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        max_amount, results = 0, []
        for candy in candies:
            max_amount = max(max_amount, candy)
        for candy in candies:
            if candy + extraCandies >= max_amount:
                results.append(True)
            else:
                results.append(False)
        return results
fockspaces commented 1 year ago

From GPT:

  1. 最大值可以直接用 max function,而不需透過 for 來掃
  2. append 甚至可以放判斷式,不用特別用 condition 區分
class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        max_amount, results = max(candies), []
        for candy in candies:
            results.append(candy + extraCandies >= max_amount)
        return results