LeetCode

来源:互联网 发布:mac视频截图快捷键 编辑:程序博客网 时间:2024/06/06 12:45

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

Example 1:

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.

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

Subscribe to see which companies asked this question.


题意:给出一个只含0/1的数组,求最大的连续1的个数

思路:扫一遍统计就好了


class Solution {public:    int findMaxConsecutiveOnes(vector<int>& nums) {        int len = nums.size();        int cnt = 0;        int ans = 0;        for (int i = 0; i < len; i++) {            if (nums[i] == 0) {                ans = max(ans, cnt);                cnt = 0;            }            else cnt++;        }        ans = max(ans, cnt);   //最后也要统计一次        return ans;    }};


0 0
原创粉丝点击