LeetCode Teemo Attacking

LeetCode Teemo Attacking In LLP 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.

这个题目好长,但是很简单。因为数组是递增的,我们把每段的结束时间减去开始时间就是这个数对应的持续时间,结束时间好算,就是timeSeries[i]+duration,但是开始时间要从上一段攻击的结束时间和当前开始时间求最大值,因为有可能上一段攻击还没结束,这一段攻击就开始了。 另外例子中每秒是有持续的时间的,比如第2秒有开始时间和结束时间,不用管它,按正常的第1秒开始攻击,持续2秒,就到第3秒了(题目中是第1秒开始到第1秒结束是1秒,然后第2秒开始到第2秒结束又是1秒,所以持续2秒的话,是在第2秒结束的时候结束的)。 完整代码如下: [cpp] class Solution { public: int findPoisonedDuration(vector<int>& timeSeries, int duration) { int ans = 0, start = 0, end = 0; for (int i = 0; i < timeSeries.size(); ++i) { start = max(start, timeSeries[i]); end = timeSeries[i] + duration; ans += end – start; start = end; } return ans; } }; [/cpp] 本代码提交AC,用时62MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *