Description:
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
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.
Note:
- The input array will only contain
0
and1
. - The length of input array is a positive integer and will not exceed 10,000
思路:本题要求一串二进制中最长连续 1 的个数。遍历数组,依次更新每个连续 1 的个数,记录下最大的那个即为所求解。
C++ 代码
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int count=0; int max = 0; for(int i=0; i<nums.size();i++){ if (nums[i] == 1) ++count; if (nums[i] == 0) count = 0; if (max < count) max = count; } return max; } };
运行时间:40ms
运行内存:11.8M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于