[LeetCode] Max Consecutive Ones 最大连续1的个数

简介:

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

 

这道题让我们求最大连续1的个数,不是一道难题。我们可以遍历一遍数组,用一个计数器cnt来统计1的个数,方法是如果当前数字为0,那么cnt重置为0,如果不是0,cnt自增1,然后每次更新结果res即可,参见代码如下:

解法一:

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0, cnt = 0;
        for (int num : nums) {
            cnt = (num == 0) ? 0 : cnt + 1;
            res = max(res, cnt);
        }
        return res;
    }
};

由于是个二进制数组,所以数组中的数字只能是0或1,那么连续1的和跟个数相等,所以我们可以计算和,通过加上num,再乘以num来计算,如果当前数字是0,那么sum就被重置为0,还是要更新结果res,参见代码如下:

解法二:

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0, sum = 0;
        for (int num : nums) {
            sum = (sum + num) * num;
            res = max(res, sum);
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:最大连续1的个数Max Consecutive Ones ,如需转载请自行联系原博主。

相关文章
|
算法
LeetCode 363. Max Sum of Rect No Larger Than K
给定一个非空二维矩阵 matrix 和一个整数 k,找到这个矩阵内部不大于 k 的最大矩形和。
77 0
LeetCode 363. Max Sum of Rect No Larger Than K
LeetCode 149. Max Points on a Line
给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
80 0
LeetCode 149. Max Points on a Line
|
算法
LeetCode 128. Longest Consecutive Sequence
给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
66 0
LeetCode 128. Longest Consecutive Sequence
LeetCode之Max Consecutive Ones
LeetCode之Max Consecutive Ones
116 0
|
Java Python
LeetCode 485:连续最大1的个数 Max Consecutive Ones(python java)
公众号:爱写bug 给定一个二进制数组, 计算其中最大连续1的个数。 Given a binary array, find the maximum number of consecutive 1s in this array. 示例 1: 输入: [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3. 注意: 输入的数组只包含 0 和1。
827 0
|
Java
[LeetCode]Max Area of Island 岛屿的最大面积
链接:https://leetcode.com/problems/max-area-of-island/description/难度:Easy题目:695.
853 0
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0