495. Teemo Attacking
问题:
给定一个攻击时间点数组,和每一次攻击所持续的时间长度。
求在攻击时间点数组的攻击下,一共能持续多久。
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: You may assume the length of given time series array won't exceed 10000. 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.
解决方法:
攻击效果不会叠加,每次攻击的持续时间duration不变,则有每个时间点间隔中,攻击持续时长为:
res += min(duration, timeSeries[i] - timeSeries[i-1]);
参考代码:
1 class Solution { 2 public: 3 int findPoisonedDuration(vector<int>& timeSeries, int duration) { 4 int res=0; 5 int i=1; 6 int curres=0; 7 if(timeSeries.size()==0) return 0; 8 for(i=1; i<timeSeries.size(); i++){ 9 curres=min(duration, timeSeries[i]-timeSeries[i-1]); 10 res+=curres; 11 } 12 res+=duration; 13 return res; 14 } 15 };