Timo Attack
Title description: In the world of "League of Legends", there is a hero named "Timo" whose attack can make the enemy hero Ashe (Editor's Note: Frost Archer) into a poisoned state. Now, given the time sequence of Teemo's attack on Ashe and the duration of the poisoning of Teemo's attack, you need to output the total duration of Ashe's poisoning state.
You can think that Teemo attacked at a given point in time and immediately put Ashe in a poisoned state.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/teemo-attacking/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Traverse the array
First, initialize a result result initial value is 0, and then traverse timeSeries , the processing process is as follows:
- If the interval between the next poisoning time and the current poisoning time is less than duration , then result to the time interval between these two times;
- If the interval between the next poisoning time and the current poisoning time is greater than duration , then result duration .
After traversing, you need to add result the last poisoning time that is , and finally return result the total duration of the poisoning state.
/**
* @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));
}
}
【Daily Message】 Don’t doubt the existence of an oasis of life when encountering a desert; don’t doubt the realization of life goals when encountering difficulties.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。