zoukankan      html  css  js  c++  java
  • LeetCode Array Easy 485. Max Consecutive Ones

     Description

    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连续出现的最多次数

    我的思路:定义两个变量,一个counter 记录出现次数,一个temp 记录当前出现次数, 如果遇0则temp归零重新计数。同时考虑边界情况

    public int FindMaxConsecutiveOnes(int[] nums) {
            if(nums.Length == 0)
                return 0;
            int counter = 0;
            int temp = 0;
            for(int i = 0; i < nums.Length; i++){
                if(nums[i] == 1)
                {
                    temp++;
                }else
                {
                    if(temp > counter)
                    {
                        counter = temp;
                    }
                    temp = 0; 
                }
            }
            if(temp > counter)
            {
                counter = temp;
            }
    
            return counter;
        }

  • 相关阅读:
    浅谈线段树
    浅谈KMP
    20200729线上模拟题解
    20200727线上模拟题解
    声明
    tarjan--割点,缩点
    20201029模拟
    高精模板
    二分图--二分图的几种模型
    树的直径与树的重心
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9671682.html
Copyright © 2011-2022 走看看