[LeetCode By Go 17]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

题目大意:

给定一个二进制数组,计算数组中出现的最大连续1的个数。
注意

  • 输入数组只包含0和1
  • 数组长度是正整数并且不会超过10000

解题思路

遍历整个数组,分别计算每个连续1的长度,并求出最大长度,时间复杂度为O(1).

代码

maxConsecutiveOnes.go

package _485_Max_Consecutive_Ones

func FindMaxConsecutiveOnes(nums []int) int {
    var maxConsecutiveOnes int
    length := len(nums)
    for i := 0; i < length; {
        if 0 == nums[i] {
            i++
            continue
        } else {
            consecutiveOnes := 1

            for i++; i< length && 1 == nums[i]; i++ {
                    consecutiveOnes++
            }
            if consecutiveOnes > maxConsecutiveOnes {
                maxConsecutiveOnes = consecutiveOnes
            }
        }
    }

    return maxConsecutiveOnes
}

测试代码

maxConsecutiveOnes_test.go

package _485_Max_Consecutive_Ones

import "testing"

func TestFindMaxConsecutiveOnes(t *testing.T) {
    input := []int{1,1,0,1,1,1}
    want := 3

    ret := FindMaxConsecutiveOnes(input)

    if want == ret {
        t.Logf("pass")
    } else {
        t.Errorf("fail, want %+v, get %+v", want, ret)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • python入门 基本的数据类型 在Python中,能够直接处理的数据类型有以下几种: 整数 Python可以处理...
    洺樂阅读 199评论 0 0
  • 互相倾诉倾听,取长补短。把自己放在这段关系里最平衡的位置上,舒服没有压迫感。是我认为的最合适的友谊。 我们在夏日午...
    十一月四十阅读 180评论 0 1
  • 风连翼自从娶了凰北月,一直想要个孩子,可是,凰北月答应嫁给他的原因,就是要做丁克,不给他生子。 她的性格不是以前的...
    素婉纤尘阅读 14,462评论 3 10
  • 1.首先是cookie的基本用法: 日常开发中可以使用cookie来保持状态来达到保持连接的功能,日常开发中常用s...
    senninha阅读 403评论 0 0