2018-09-08 11:49:55 +00:00
|
|
|
|
# [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/description/)
|
|
|
|
|
# 思路
|
|
|
|
|
从前往后遍历数组,用max记录后面要返回的结果,用current记录当前连续1的个数,对于nums[i]:
|
|
|
|
|
* 若nums[i] == 1, current += 1即可;
|
|
|
|
|
* 否则,若current大于0,表示前一个元素是0当前元素是1,则对比current和max看是否更新max,然后将current置0。
|
|
|
|
|
|
|
|
|
|
注意跳出循环后也要判断一次是否更新max。
|
|
|
|
|
|
|
|
|
|
# C++
|
2019-09-13 15:08:41 +00:00
|
|
|
|
```C++
|
2018-09-08 11:49:55 +00:00
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
int findMaxConsecutiveOnes(vector<int>& nums) {
|
|
|
|
|
int max = 0, current = 0;
|
|
|
|
|
for(int i = 0; i < nums.size(); i++){
|
|
|
|
|
if(nums[i]) current += 1;
|
|
|
|
|
else if(current > 0){ // 这里直接else也可以但是时间会慢一些
|
|
|
|
|
if(current > max) max = current;
|
|
|
|
|
current = 0;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if(current > max) max = current;
|
|
|
|
|
return max;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|