前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:485. Max Consecutive Ones

LeetCode笔记:485. Max Consecutive Ones

作者头像
Cloudox
发布2021-11-23 14:25:42
1870
发布2021-11-23 14:25:42
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题(Easy):

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:

  1. The input array will only contain 0 and 1.
  2. The length of input array is a positive integer and will not exceed 10,000

大意:

给出一个二进制数组,在数组中找到连续的1最大的长度。 例1: 输入:[1,1,0,1,1,1] 输出:3 解释:开头两个数字和最后三个数字是连续的1。 最大的连续的1是3个。 注意:

  1. 输入的数组只包含0和1。
  2. 输入数组的长度是个正整数且不超过10000。

思路:

无非就是遍历数组,检查连续的1,用一个临时变量记录每次连续的1的个数,连续结束时判断是否比最大的连续个数要大。

代码的写法可以有很多种,也会随着写法不同带来一些效率差异,但时间复杂度是一样的。

代码(C++):

代码语言:javascript
复制
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0;
        int temp = 0;
        bool flag = true;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 1) {
                if (flag) temp++;
                else {
                    temp = 1;
                    flag = true;
                }
                if (temp > res) res = temp;
            } else 
                if (flag) flag = false;
        }
        return res;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/1/17 上,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题(Easy):
  • 大意:
  • 思路:
  • 代码(C++):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档