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.
Example 1:
Input: timeSeries = [1,4], duration = 2 Output: 4 Explanation: Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
Example 2:
Input: timeSeries = [1,2], duration = 2 Output: 3 Explanation: Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
Constraints:
1 <= timeSeries.length <= 1040 <= timeSeries[i], duration <= 107timeSeries is sorted in non-decreasing order.这道题好像没啥技巧……就顺着思路写。遍历数组,如果当前数字的下一个比它加上duration大,那就能attack到duration那么长时间,否则就只attack到下一个数字-当前数字的时间。因为最后一次必定能attack到duration那么长时间,所以遍历到倒数第二个就行,最后无脑加上duration返回。
Runtime: 4 ms, faster than 63.73% of Java online submissions for Teemo Attacking.
Memory Usage: 54 MB, less than 65.24% of Java online submissions for Teemo Attacking.
- class Solution {
- public int findPoisonedDuration(int[] timeSeries, int duration) {
- int result = 0;
- int i = 0;
- while (i < timeSeries.length - 1) {
- int end = timeSeries[i] + duration;
- if (timeSeries[i + 1] > end) {
- result += duration;
- } else {
- result += (timeSeries[i + 1] - timeSeries[i]);
- }
- i++;
- }
- return result + duration;
- }
- }
然后看了discussion发现有人提出可以采用merge interval的思想,用两个变量start和end来记录当前attack的开始和结束时间。如果当前数字比end大,说明此次attack结束,result就加上end - start的时间并更新start和end;否则说明此次attack还没结束,只需要更新end。贴一个别人写的代码,就懒的自己写了……Loading...