495. Teemo Attacking【middle】&& 485. Max Consecutive Ones【easy】 02-24

495 題目描述【middle】

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.

//意思就是求Ashe被攻擊且中毒的時間總和,每次中毒立即生效,因此上述例子輸出的是3,1s攻擊但中毒1s,2s又攻擊中毒2s,而不是兩次攻擊簡單相加2+2 = 4s

思路

遍歷數組,取出當前遍歷的值和下一個值,判斷當前值+中毒時間與下一個值的大小:

1)當前值+中毒時間 > 下一個值,則中毒總時間只能加下一個值 - 當前值

2)否則,中毒總時間加上單次中毒時間


代碼

class Solution {
public:
	int findPoisonedDuration(vector<int>& timeSeries, int duration) {
		int count = 0;
		vector<int>::iterator it = timeSeries.begin();

		if (timeSeries.size()) {
			while (it + 1 != timeSeries.end()) {
				if (*it + duration > *(it + 1))
					count += *(it + 1) - (*it);

				else
					count += duration;

				it++;
			}
			count += duration;
		}

		return count;
	}
};



———————————————我是分割線——————————————————


485題目描述【easy】

Input: [1,1,0,1,1,1]Output: 3Explanation: The first two digits or the last three digits are consecutive 1s.The maximum number of consecutive 1s is 3.

思路

遍歷數組,當元素爲 1 時計數器加 1,否則計數器的值存入臨時數組然後置零,接着遍歷直到結束

代碼

class Solution {
public:
	int findMaxConsecutiveOnes(vector<int>& nums) {
		int count = 0;
		vector<int>::iterator it = nums.begin();
		vector<int> forCount;
		forCount.push_back(0);

		while (it != nums.end()) {
			if (*it == 1) 
				count++;
				
			else {
				forCount.push_back(count);
				count = 0;
			}

			it++;
		}

		if (count != 0)
			forCount.push_back(count);

		sort(forCount.begin(), forCount.end());
		return forCount[forCount.size()-1];
	}
};


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