495. Teemo Attacking

来源:互联网 发布:注册知乎提示id不匹配 编辑:程序博客网 时间:2024/05/16 08:17

Example 1:

Input: [1,4], 2Output: 4Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. 
This poisoned status will last 2 seconds until the end of time point 2.
And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds.
So you finally need to output 4.

Example 2:

Input: [1,2], 2Output: 3Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. 
This poisoned status will last 2 seconds until the end of time point 2.
However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status.
Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
So you finally need to output 3.

public class Solution {    public int findPoisonedDuration(int[] timeSeries, int duration) {        int m = 0;        if(timeSeries.length == 0 || timeSeries == null || duration == 0)  return m;        if(timeSeries.length == 1) {           return m = duration;        } else {            for(int i = 1; i < timeSeries.length; i++){                if(timeSeries[i] - timeSeries[i-1] > duration) {                    m += duration;                } else {                    m += timeSeries[i] - timeSeries[i-1];                }            }        }                return m + duration;    }}
看了别的的,思路相同,但是写法更加简便,以后多用for each 和三元运算符

public int findPoisonedDuration(int[] timeSeries, int duration) {        if (timeSeries.length == 0) return 0;        int begin = timeSeries[0], total = 0;        for (int t : timeSeries) {            total+= t < begin + duration ? t - begin : duration;            begin = t;        }           return total + duration;    } 



                                                 
    0 0
    原创粉丝点击