3

LeetCode-495-提莫攻击

 2 years ago
source link: https://segmentfault.com/a/1190000040773291
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-495-提莫攻击

发布于 今天 02:10

题目描述:在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄,他的攻击可以让敌方英雄艾希(编者注:寒冰射手)进入中毒状态。现在,给出提莫对艾希的攻击时间序列和提莫攻击的中毒持续时间,你需要输出艾希的中毒状态总时长。

你可以认为提莫在给定的时间点进行攻击,并立即使艾希处于中毒状态。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:遍历数组

首先,初始化一个结果result初始值为0,然后遍历timeSeries中的元素,处理过程如下:

  • 如果下一次的中毒时间和本次的中毒时间间隔小于duration,则将result加这两次的时间间隔;
  • 如果下一次的中毒时间和本次的中毒时间间隔大于duration,则将result加上duration

遍历完后,需要将result加上最后一次的中毒时间即duration,最后返回result即为中毒状态总时长。

/**
 * @Author: ck
 * @Date: 2021/10/3 11:22 上午
 */
public class LeetCode_495 {
    public static int findPoisonedDuration(int[] timeSeries, int duration) {
        int result = 0;
        for (int i = 0; i < timeSeries.length - 1; i++) {
            if (timeSeries[i + 1] - timeSeries[i] < duration) {
                result += timeSeries[i + 1] - timeSeries[i];
            } else {
                result += duration;
            }
        }
        result += duration;
        return result;
    }

    public static void main(String[] args) {
        System.out.println(findPoisonedDuration(new int[]{1, 2}, 2));
    }
}

【每日寄语】 不要一遇沙漠,就怀疑生命绿洲的存在;不要一遇到困难,就怀疑人生目标的实现。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK