leetcode-495.提莫攻击
leetcode-495.提莫攻击
文章目录
- leetcode-495.提莫攻击
- 一.题目描述
- 二.代码提交
- 三.解释
一.题目描述
二.代码提交
#include <vector>
using namespace std;
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int total = 0;
for (int i = 0; i < timeSeries.size(); ++i) {
if (i == timeSeries.size() - 1)
total += duration; // 最后一次攻击的毒持续完整时间
else
total += min(timeSeries[i + 1] - timeSeries[i], duration); // 计算中毒时间
}
return total;
}
三.解释
- 遍历攻击时间数组
timeSeries
。 - 每次攻击持续
duration
时间,但如果下一次攻击发生在毒药效果结束之前,则中毒时间为两次攻击的间隔。 - 使用
min
函数取间隔时间和毒药持续时间的最小值,累加到总时间。 - 最后返回总中毒时间。