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

来源:互联网 发布:sql清空表中记录 编辑:程序博客网 时间:2024/06/06 15:41

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);elsecount += 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];}};


0 0
原创粉丝点击