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 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

解答:题目的意思是给一个数组,里面的元素只有0和1,求出连续1的个数最大值。

    1、首先遍历整个数组,用变量sum记录连续1的个数,变量max记录连续个数的最大值

    2、遍历到第一个1时,变量sum开始计数;继续往下遍历,遇到0结束,判断:sum是否大于当前max的值,如果大于,则sum为所求值,赋值给max,若sum小于max的值,则继续往下遍历,直到遇到下一个1,sum再次计数,记录连续1的个数

    3、重复上述操作,直到遍历完整个数组

代码如下:

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) { 
        int i = 0,max=0,sum=0;
    for(i=0;i<nums.size();i++){
        if(nums[i] == 1){ //从第一个1开始计数
             while(nums[i] == 1){
                 sum++;
                 i++;
             }
             //遇到0,退出循环
            if(sum> max){ //判断与max的大小,如果sum大于max则赋值给max
                max=sum;
            }
            sum=0; //sum重置为0,继续往下遍历
         }
     }
     return max;
   }       
}; 
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐