LeetCode 485. Max Consecutive Ones

来源:互联网 发布:圣诞唱诗班歌曲知乎 编辑:程序博客网 时间:2024/06/05 03:12

485. Max Consecutive Ones

一、问题描述

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

二、输入输出

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

三、解题思路

  • 非常简单,按照题目来做,遍历数组,当遇到1的时候开始连续遍历并记录下连续出现的1的个数,如果这个个数超过maxLen就更新maxLen
  • 最后maxLen就是最多的连续1的个数
class Solution {public:    int findMaxConsecutiveOnes(vector<int>& nums) {        int maxLen = 0, n = nums.size();        for (int i = 0; i < n; ) {            if (nums[i] != 1){                i++;                continue;            }            int curLen = 0;            while(i < n && nums[i] == 1){                curLen++;                i++;            }            if(curLen > maxLen) maxLen = curLen;        }        return maxLen;    }};
原创粉丝点击