• 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...

  • 相关阅读:
    Matlab彩色图像卷积的数学原理及纯手工实现
    【Vue.js设计与实现】第4章 响应系统的作用与实现
    职场人,该看重机遇,还是该注重自己的能力?
    【无标题】Linux服务器上监控网络带宽的18个常用命令
    【附源码】计算机毕业设计SSM网上书城系统
    Python遥感开发之arcpy批量投影栅格
    2022杭电多校九 1008-Shortest Path in GCD Graph(质因子+容斥)
    优选商机+沃视获客+外呼系统+智能CRM
    vue-router的安装和使用
    Android 11.0 默认开启开发者模式和开启usb调试模式
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127574361