Description:
https://leetcode.com/problems/teemo-attacking/description/
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution { public: int findPoisonedDuration(vector<int>& timeSeries, int duration) { if (timeSeries.size() == 0) return 0; int time = duration; for (int i = 0; i < timeSeries.size() - 1;i++) { if (timeSeries[i+1] > timeSeries[i] + duration - 1) time += duration; else time += timeSeries[i+1] - timeSeries[i]; } return time; } }; |
Time & Space:
O(n) & O(1)
A shorter version:
class Solution {
public:
int findPoisonedDuration(vector& timeSeries, int duration) {
int ans = 0, awake = 0;
for (auto x : timeSeries) {
ans += (x > awake) ? duration : x + duration – awake;
awake = x + duration;
}
return ans;
}
};