LeetCode Array Problem || 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.
错误尝试
一开始没多想,试图开一个bool数组用来记录每一个时间段的poison情况,用于判断是否重叠……
class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int psize = timeSeries.back() + duration;
int pois[psize];
memset(pois, 0, sizeof(pois));
int sum = 0;
for(int i = 0; i <= timeSeries.size() - 1; i++){
for(int j = timeSeries[i]; j <= timeSeries[i] + duration - 1; j++){
if(pois[j] == 0){
sum ++;
pois[j] = 1;
}
}
}
return sum;
}
};
这样开辟的数组太大了,果断Runtime Error
正确解法
于是考虑设计一个变量last用于记录上一次poison的结束时间,last初始值为0。
分三种情况解决重叠问题:
- timeSeries[i]大于或等于last,完全无重叠,总时间增长duration;
- timeSeries[i]加上duration后比last大,部分重叠,总时间增长duration减去重叠部分;
- timeSeries[i]加上duration后比last小,完全不重叠,不进行操作;
class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int sum = 0;
int last = 0;
for(int i = 0; i < timeSeries.size(); i++) {
if(timeSeries[i] >= last) {
sum += duration;
last = timeSeries[i] + duration;
}
else if(timeSeries[i] + duration > last) {
int add = duration - (last - timeSeries[i] );
sum += add;
last = timeSeries[i] + duration;
}
}
return sum;
}
};
心得体会
这题在LeetCode中难度medium,在Array题库里算是比较简单的,一开始太naive试图暴力解决,然而这是不行的。在关于last的设定问题上也是踩过几下坑,一直wrong answer,调整了几次解决。