Java O(n) approach


  • 0
    L

    This problem can be solved by a single iteration.
    It only has two conditions:

    1. The time between two attacks is smaller than or equal to the "duration". In this case, you only have to add the time difference between two attacks.
    2. The time between two attacks is greater than the "duration". In this case, you just need to add the "duration".

    Also, do not forget to add the last poison peroid to your result.
    ...

    public int findPoisonedDuration(int[] timeSeries, int duration) {
        
        int len = timeSeries.length;
        
        if (len == 0) {
            return 0;
        }
        
        if (len == 1) {
            return duration;
        }
        
        int time = 0;
        for (int i =1; i < len; i++) {
            int diff = timeSeries[i] - timeSeries[i-1];
            
            if (diff <= duration) {
                time += diff;
            }else {
                time += duration;
            }
        }
        time += duration;
        
        return time;
    }
    

    ...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.