[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)
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/d0f763ac4dfa
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞