[Array]495.Teemo Attacking

来源:互联网 发布:数据分析 培训 上海 编辑:程序博客网 时间:2024/06/18 11:27

Example 1:

Input: [1,4], 2Output: 4Explanation: 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], 2Output: 3Explanation: 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.
Solution
class Solution {public:    int findPoisonedDuration(vector<int>& timeSeries, int duration) {        int size = timeSeries.size();        int i=0, j=0, tmpSum = duration, totalSum=0;        while (i<size){            tmpSum += timeSeries[i];            for (j=i+1;j<size;j++){                if (tmpSum>=timeSeries[j]) {                   tmpSum = timeSeries[j]+duration;                }                else{                    break;                }            }            totalSum += (tmpSum-timeSeries[i]);            cout << "totalSum:" << totalSum<< endl;            i = j;            tmpSum=duration;        }        return totalSum;    }};
0 0
原创粉丝点击