iT邦幫忙

0

leetcode with python:495. Teemo Attacking

  • 分享至 

  • xImage
  •  

題目:

Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.

You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.

Return the total number of seconds that Ashe is poisoned.

提摩用毒攻擊艾希
給定一個陣列(sorted)表示在第幾秒攻擊,且給定毒會持續幾秒
回傳艾希共中毒幾秒

沒想到寫個leetcode也會碰到lol...

class Solution:
    def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
        ans=0
        bound=0
        
        for i in timeSeries:
            x=max(bound,i)
            ans=ans+i+duration-x
            bound=i+duration
                
        return ans

用ans紀錄毒持續的秒數,bound紀錄上次中毒結束是在第幾秒
遍歷所有受到攻擊的秒數(i)
每次選擇i和bound較大者作為起點(x)
才不會重複計算中毒的秒數

如在第1,2秒受到攻擊,而毒的持續時間為2秒
那中毒秒數分別為1,2和2,3
我們需要考量到重複計算到第2秒的可能

ans加上每次終點(i+duration)減去起點的秒數(x)
bound更新為新終點(i+duration)
遍歷完回傳ans
最後執行時間267ms(faster than 94.06%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言