• 495. Teemo Attacking


    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 <= 104
    • 0 <= timeSeries[i], duration <= 107
    • timeSeries 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.

    1. class Solution {
    2. public int findPoisonedDuration(int[] timeSeries, int duration) {
    3. int result = 0;
    4. int i = 0;
    5. while (i < timeSeries.length - 1) {
    6. int end = timeSeries[i] + duration;
    7. if (timeSeries[i + 1] > end) {
    8. result += duration;
    9. } else {
    10. result += (timeSeries[i + 1] - timeSeries[i]);
    11. }
    12. i++;
    13. }
    14. return result + duration;
    15. }
    16. }

    然后看了discussion发现有人提出可以采用merge interval的思想,用两个变量start和end来记录当前attack的开始和结束时间。如果当前数字比end大,说明此次attack结束,result就加上end - start的时间并更新start和end;否则说明此次attack还没结束,只需要更新end。贴一个别人写的代码,就懒的自己写了……Loading...

  • 相关阅读:
    王杰qtday4
    Spring入门
    如何证明特征值的几何重数不超过代数重数
    <栈和队列及模拟实现>——《Data Structure in C Train》
    redis学习四redis消息订阅、pipeline、事务、modules、布隆过滤器、缓存LRU
    c语言:三个数排序(if-else实现)
    中创人民云|党管数据是如何保证国家数据安全的
    CISAW信息安全保障人员认证考试难吗?
    使用Jmeter+ant进行接口自动化测试(数据驱动)
    快递管理系统 毕业设计 JAVA+Vue+SpringBoot+MySQL
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127574361