LintCode 1207. Timo attacks JavaScript algorithms

description

In LOL, there is a hero named "Timo" whose attack can make the enemy Ashe enter a poisoned state. Now given the ascending sequence of Teemo’s attack time points, and the duration of the poisoning of each Teemo’s attack, the total time of Ashe’s poisoning state is output.

Assume that Teemo attacked at the beginning of each specific time slice, and Ashe was immediately poisoned.

Description

  • Assume that the length of a given time series will not exceed 10,000.
  • Assume that the time series of Teemo's attack and the duration of his poisoning are both non-negative integers and will not exceed 10,000,000.

Sample

- 样例 1:
样例: [1,4], 2
输出: 4
解释: 在第1秒开头, 提莫攻击了艾希,艾希立刻中毒。 
这次中毒持续2秒,直到第2秒末尾。 
在第4秒开头, 提莫又攻击了艾希, 又让艾希中毒了2秒。. 
所以最终结果是4.


- 样例 2:
输入: [1,2], 2
输出: 3
解释:1秒钟开头,  提莫攻击了艾希,艾希立刻中毒。 
这次中毒持续2秒,直到第2秒末尾。
然而,第2秒初,提莫又攻击了艾希,而艾希还处在中毒态。
由于中毒态不会叠加, 所以中毒态会在3秒末停止。 
所以,最终返回3

challenge

Obviously you can return a + b directly, but can you challenge it not to do so? (Do not use arithmetic operators such as ++)

Parsing

findPoisonedDuration = function (timeSeries, duration) {
    
    
    if (timeSeries == null || timeSeries.length == 0 || duration == 0) {
    
    
        return 0;
    }
    result = 0, start = timeSeries[0], end = timeSeries[0] + duration;
    for (i = 1; i < timeSeries.length; i++) {
    
    
        if (timeSeries[i] > end) {
    
    
            result += end - start;
            start = timeSeries[i];
        }
        end = timeSeries[i] + duration;
    }
    result += end - start;
    return result;
}

operation result

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/SmallTeddy/article/details/108635684