[LeetCode]485. Max Consecutive Ones

[LeetCode]485. Max Consecutive Ones

题目描述

[LeetCode]485. Max Consecutive Ones_第1张图片

思路

遍历数组
如果为1,计数加
如果为0或数组最后一位,max更新,计数重置

代码

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int max = 0, count = 0;
        for (int i = 0; i < nums.size(); ++i){
            if (nums[i]){
                ++count;
            }
            if ((!nums[i]) || i == nums.size() - 1){
                if (count > max) {
                    max = count;
                }
                count = 0;
            }
        }
        return max;
    }
};

你可能感兴趣的:(leetcode,leetcode)