본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 495. Teemo Attacking.cpp

반응형

https://leetcode.com/problems/teemo-attacking/description/

 

Teemo Attacking - LeetCode

Can you solve this real interview question? Teemo Attacking - Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

ashe가 독에 당한 전체 시간 totalPoisoned와 다음 독이 풀리는 시점을 저장할 변수 next를 선언해 0으로 초기화해줍니다.

📔 풀이과정

공격을 받았던 시간이 저장된 vector timeSeries에 대해 for loop를 수행하며 다음을 확인해줍니다.

1. next를 갱신해주기 전에 독이 풀리는 시간이 t보다 큰지 확인해줍니다.

   이 경우 t시점에 공격을 받았을 때 duration만큼 더해주는 것이 아닌 겹치는 구간을 빼줘야 합니다. 이는 초록색 선으로 표시된 구간으로 next - t 만큼입니다. 따라서 t시점에 공격당했을 때 독에 당한 시간은 duration - (next - t) 만큼이 됩니다. 이 값을 totalPoisoned에 더해줍니다.

2. 이외의 경우에는 겹치지 않기 때문에 duration을 그대로 totalPoisoned에 더해주면 됩니다.

3. t시점에 공격 당했으므로 독에 풀리는 시간 next를 t + duration으로 갱신해줍니다.

📔 정답 출력 | 반환

totalPoisoned를 반환해줍니다.

📕 Code

📔 C++

class Solution {
public:
    int findPoisonedDuration(vector<int>& timeSeries, int duration) {
        int totalPoisoned = 0;
        int next = 0;
        for(auto t : timeSeries) {
            if(next > t) {
                totalPoisoned += duration - (next - t);
            }
            else {
                totalPoisoned += duration;
            }
            next = t + duration;
        }

        return totalPoisoned;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.