LeetCode Array Problem || Teemo Attacking

LeetCode Array Problem || Teemo Attacking

题目描述

In LLP world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo’s attacking ascending time series towards Ashe and the poisoning time duration per Teemo’s attacking, you need to output the total time that Ashe is in poisoned condition.
You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.
这里写图片描述


错误尝试

一开始没多想,试图开一个bool数组用来记录每一个时间段的poison情况,用于判断是否重叠……

class Solution {
public:
    int findPoisonedDuration(vector<int>& timeSeries, int duration) {
        int psize = timeSeries.back() + duration;
        int pois[psize];
        memset(pois, 0, sizeof(pois));
        int sum = 0;
        for(int i = 0; i <= timeSeries.size() - 1; i++){
            for(int j = timeSeries[i]; j <= timeSeries[i] + duration - 1; j++){
                if(pois[j] == 0){
                   sum ++;
                   pois[j] = 1;
                }
            }
        }
        return sum;
    }
};

这样开辟的数组太大了,果断Runtime Error


正确解法

于是考虑设计一个变量last用于记录上一次poison的结束时间,last初始值为0。
分三种情况解决重叠问题:

  1. timeSeries[i]大于或等于last,完全无重叠,总时间增长duration;
  2. timeSeries[i]加上duration后比last大,部分重叠,总时间增长duration减去重叠部分;
  3. timeSeries[i]加上duration后比last小,完全不重叠,不进行操作;
class Solution {
public:
    int findPoisonedDuration(vector<int>& timeSeries, int duration) {
        int sum = 0;
        int last = 0;
        for(int i = 0; i < timeSeries.size(); i++) {
            if(timeSeries[i] >= last) {
                sum += duration;
                last = timeSeries[i] + duration;
            }
            else if(timeSeries[i] + duration > last) {
                int add = duration - (last - timeSeries[i] );
                sum += add;
                last = timeSeries[i] + duration;
            }
        }
        return sum;
    }
};

心得体会

这题在LeetCode中难度medium,在Array题库里算是比较简单的,一开始太naive试图暴力解决,然而这是不行的。在关于last的设定问题上也是踩过几下坑,一直wrong answer,调整了几次解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值