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.

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的最多次数。这个题就是充分利用了数组中只有0和1的特性,如果数组中全部都是0那么返回的数字就是0(因为没有1出现)。除此之外,可以遍历一边数组,然后判断每个元素是不是等于0,如果不等于0的话,就让标志位+1,并与此时的max数比较,如果大于max数就让max数等于该数字即可,如果等于0的话,将标志位置0即可。

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int maxnum = 0;
        int maxHere = 0;
        for(int num : nums) {
            maxHere = (num == 0) ? 0 : maxHere + 1;//如果此刻是0,则让maxHere等于0,否则maxHere加1
            if(maxHere > maxnum) {
                maxnum = maxHere;
            }
        }
        return maxnum;
    }
};

还有一种表达方法,不过都是利用了0和1的特性,定义一个sum初始化为0,然后遍历数组,先将sum和数组此刻的元素num相加并乘以num,最后赋值为sum,如果此时num为0的话,那么sum算出来也就是0。如果不是0的话,算出来就是sum+num的数,如果连着都是1的话算出来也就是累加的和。

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int maxnum = 0;
        int sum = 0;
        for(int num : nums) {
            sum = (num + sum) * num;//如果此刻num为0,则sum就为0,否则就是num+sum
            if(maxnum < sum) {
                maxnum = sum;
            }
        }
        return maxnum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值