问题描述:
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.
解释说明:timeSeries数组给出了我方发动攻击的时间,敌方受到攻击后中毒duration时间,若我方在敌人中毒时继续打击敌人,敌人中毒时间重置,计算中毒时间之和.
思路:如果下一个攻击距离本次攻击较远(即:这次+时长-1<下次),则说明duration时长全部利用上了,累加之;若下一次攻击距离这次攻击较近(即:这次+时长-1>=下次),则说明duration没有被利用完,本次中毒只持续(下次-这次)之长。鉴于这样的思路,要注意最后一次攻击没有下次,所以最后一次攻击要单独考虑
代码如下:
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int counter=0;
for(int i=0; i<timeSeries.length-1; i++){
if(timeSeries[i]+duration-1<timeSeries[i+1]){//make full use of this poisoned period
counter=counter+duration;
}
else{//poispned time = next-this
counter=counter+timeSeries[i+1]-timeSeries[i];
}
}
return counter+duration; //count the last period of time manually
}
}
时间复杂度: O(n)