LeetCode485 Max Consecutive Ones

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

Given a binary array, find the maximum number of consecutive 1s in this array.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

样例

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

思路

给一个0-1数组,求数组中最长的连续1的个数。
循环模拟一遍,遇到非1的数字,更新最长的答案即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
nums.push_back(-1); // 为了方便处理,在数组末尾加入一个非1的数字
int ans = 0, cnt = 0;
for (auto x : nums) {
if (x == 1) cnt++;
else {
ans = max(ans, cnt);
cnt = 0;
}
}
return ans;
}
};
分享到 评论