LeetCode-485 Max Consecutive Ones

来源:互联网 发布:汉仪中黑简体下载 mac 编辑:程序博客网 时间:2024/06/03 17:46

题目描述只有一句话

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

给一个二进制数组,找 1 的最长连续子串,输出其长度

思路为设一个变量temp作为统计连续1的个数,从头开始统计,假设当前位为1,则 temp++,否则连续被打断,ans与temp作比较,取大者,temp更新为零,继续向下统计,因为最后一位可能是1,所以要在循环外加一个比较,返回大者

题目链接

代码如下:

class Solution {public:    int findMaxConsecutiveOnes(vector<int>& nums) {        int ans = 0, temp = 0;    for (int i = 0; i < (int)nums.size(); i++) {    if (nums[i]) temp++;    else {    ans = max(temp, ans);    temp = 0;    }    }    return max(ans, temp);    }};