題目
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
題目大意:
給定一個(gè)二進(jìn)制數(shù)組拼坎,計(jì)算數(shù)組中出現(xiàn)的最大連續(xù)1的個(gè)數(shù)箩帚。
注意:
- 輸入數(shù)組只包含0和1
- 數(shù)組長(zhǎng)度是正整數(shù)并且不會(huì)超過10000
解題思路
遍歷整個(gè)數(shù)組,分別計(jì)算每個(gè)連續(xù)1的長(zhǎng)度躬络,并求出最大長(zhǎng)度,時(shí)間復(fù)雜度為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
}
測(cè)試代碼
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)
}
}