495. Teemo Attacking

선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

Наш герой Тимо атакует врага Эшу ядовитыми атаками! Когда Тимо атакует Эшу, она оказывается отравленной на ровно duration секунд. Более формально, атака в секунду t означает, что Эша будет отравлена в течение интервала времени [t, t + duration - 1] включительно. Если Тимо атакует снова до окончания эффекта яда, таймер для него сбрасывается, и эффект яда закончится через duration секунд после новой атаки.

Вам given неубывающее 정수 timeSeries, где timeSeries[i] обозначает, что Тимо атакует Эшу во вторую timeSeries[i], и 정수 duration.

return общее количество секунд, в течение которых Эша была отравлена.

예제:

Input: timeSeries = [1,4], duration = 2

Output: 4

Explanation: Teemo's attacks on Ashe go as follows:

- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.

- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.

Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.

C# 해법

매칭됨/원본
public class Solution {
    public int FindPoisonedDuration(int[] timeSeries, int duration) {
        int n = timeSeries.Length;
        if (n == 0) return 0;
        int total = 0;
        for (int i = 0; i < n - 1; ++i) {
            total += Math.Min(timeSeries[i + 1] - timeSeries[i], duration);
        }
        return total + duration;
    }
}

C++ 해법

자동 초안, 제출 전 검토
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int FindPoisonedDuration(vector<int>& timeSeries, int duration) {
        int n = timeSeries.size();
        if (n == 0) return 0;
        int total = 0;
        for (int i = 0; i < n - 1; ++i) {
            total += min(timeSeries[i + 1] - timeSeries[i], duration);
        }
        return total + duration;
    }
}

Java 해법

매칭됨/원본
class Solution {
  public int findPoisonedDuration(int[] timeSeries, int duration) {
    int n = timeSeries.length;
    if (n == 0) return 0;

    int total = 0;
    for(int i = 0; i < n - 1; ++i)
      total += Math.min(timeSeries[i + 1] - timeSeries[i], duration);
    return total + duration;
  }
}

JavaScript 해법

매칭됨/원본
class Solution {
    findPoisonedDuration(timeSeries, duration) {
        const n = timeSeries.length;
        if (n === 0) return 0;

        let total = 0;
        for (let i = 0; i < n - 1; i++) {
            total += Math.min(timeSeries[i + 1] - timeSeries[i], duration);
        }
        return total + duration;
    }
}

Python 해법

매칭됨/원본
class Solution:
    def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
        n = len(timeSeries)
        if n == 0:
            return 0

        total = 0
        for i in range(n - 1):
            total += min(timeSeries[i + 1] - timeSeries[i], duration)
        return total + duration

Go 해법

매칭됨/원본
func findPoisonedDuration(timeSeries []int, duration int) int {
    n := len(timeSeries)
    if n == 0 {
        return 0
    }

    total := 0
    for i := 0; i < n-1; i++ {
        total += min(timeSeries[i+1]-timeSeries[i], duration)
    }
    return total + duration
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

Algorithm

Инициализация

Инициализируйте переменную total для хранения общего времени, в течение которого Эша была отравлена. Проверьте, если 배열 timeSeries пуст, return 0.

Итерация

Пройдите по всем elementам 배열а timeSeries, кроме последнего. На каждой итерации добавьте к total минимальное значение между длительностью интервала и временем действия яда duration.

Возврат результата

return сумму total и duration, чтобы учесть последнюю атаку.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.