Leetcode495 Teemo Attacting

//  C++
In LOL 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.

Example 1:

Input: [1,4], 2
Output: 4
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. 
This poisoned status will last 2 seconds until the end of time point 2.
And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds.
So you finally need to output 4.

Example 2:

Input: [1,2], 2
Output: 3
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. 
This poisoned status will last 2 seconds until the end of time point 2.
However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status.
Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
So you finally need to output 3.

題目大意是給出Teemo攻擊時刻表,Teemo每次攻擊可以使Ashe在監獄待duration時間,攻擊效果不能累加,即若攻擊時Ashe已經在監獄中,則從當前時間從新開始使Ashe在監獄中待duration時間,輸出Ashe一共在監獄中待的時間。

思路:設置標記位sign記錄上次攻擊可以使Ashe在監獄中待到哪一時刻,與本次攻擊的時刻比較,若本次攻擊時刻大於上次攻擊後Ashe出獄時間,則Ashe在監獄待滿一個duration,否則Ashe還未出獄就又被攻擊,未待滿一個duration變從新計時,所以在監獄中待的時間爲duration減去相差的時間。

#include<iostream>
#include<vector>

using namespace std;

int findPoisonedDuration(vector<int>& timeSeries, int duration) {
	int res = 0,i;
	int sign = timeSeries[0]+duration;
	for(i = 1;i<timeSeries.size();i++){
		if(timeSeries[i]>=sign)
			res += duration;
		else
			res += duration-(sign-timeSeries[i]);
		sign = timeSeries[i] + duration;
	}
	return res+sign-timeSeries[i-1];
 }

int main(){	
	int a[] = {1,2,3,4,5};
	vector<int> v(a,a+5);
	cout<<findPoisonedDuration(v,5)<<endl;
	return 1;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章