leetcode系列485-最大连续1的个数

【题目概要】

485. Max Consecutive Ones

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.

【思路分析】

  1. 遍历一次数组,当有1时,记录当前位置,进入循环1判断,记录退出位置,计算1的个数同时与前一次的最大值比较,更新最大值,注意在内层循环变化时,使用的是外层的计数,同时更新
  2. 也可以设定一个记录1值个数的count

【代码示例】

int findMaxConsecutiveOnes(int* nums, int numsSize){
    
    int maxone = 0;
    for(int index=0; index<numsSize; index++)
    {
        int startindex = index;
        while(index<numsSize && nums[index] == 1)
        {
            index++;
        }
        if(index-startindex > maxone)
        maxone = index-startindex;
    }
    return maxone;
}

你可能感兴趣的:(LeetCode)