leetcode with python:495. Teemo Attacking

题目:

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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章