Leetcode题解 495.Teemo Attacking 【Array】

In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.

You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.

Example 1:

Input: [1,4], 2
Output: 4
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. 
This poisoned status will last 2 seconds until the end of time point 2. 
And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. 
So you finally need to output 4.

Example 2:

Input: [1,2], 2
Output: 3
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. 
This poisoned status will last 2 seconds until the end of time point 2. 
However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. 
Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3. 
So you finally need to output 3.

Note:

  1. You may assume the length of given time series array won't exceed 10000.
  2. You may assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000.

题解:大概意思就是提莫会致盲艾希,给出一个列表和一个整数,列表里面的元素(升序)代表提莫致盲艾希的时间, 整数代表提莫致盲效果的持续时间,假定提莫攻击后艾希会立即致盲。


思路:建立两个变量,total、now ,total代表总致盲时间,now代表艾希被致盲后视力回复的前一秒,初始化为-1(因时间轴从0开始,可以认为一开始艾希视力正常。所以now设为-1)


接下来从列表中依次提取时间点,设为i。

有两种情况,一种是i > now 表明提莫攻击艾希时艾希是视力正常的,此时计算total只要直接total+=duration,因为致盲时间无重叠。

第二种是 i > now - duration + 1

这种情况表明提莫攻击艾希时艾希已经被致盲,此时会刷新致盲的剩余时间,所以total += duration -(now-i+1)

now-i+1代表前一次致盲的有效时间, duration - (now-i+1)代表第二次致盲有效时间。


注意每次计算完total后now要相应地更新


Ac代码如下:

class Solution:
    def findPoisonedDuration(self, timeSeries, duration):
        """
        :type timeSeries: List[int]
        :type duration: int
        :rtype: int
        """
        total = 0
        now = -1
        for i in timeSeries:
            if i > now:
                total += duration
                now = i + duration - 1
            elif i > now - duration + 1:
                total += duration - (now - i + 1)
                now += duration - (now - i + 1)
        return total








猜你喜欢

转载自blog.csdn.net/qq_40927376/article/details/80055539
今日推荐