Leetcode: 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.

解释说明: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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值