龙熠的技术小站

Leetcode 485 Max Consecutive Ones

给一个二进制数组,即数组内元素只有0和1,找到最长的连续的1的长度


题目

1
2
3
4
5
6
7
8
描述
Given a binary array, find the maximum number of consecutive 1s in this array.
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
2
3
4
5
6
例子
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.

解题思路

用0将数组分割成新的数组,每个数组里蕴含[1,1,1…]的数组

然后遍历获取最大长度

解题

Language : swift

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
let a = nums.split(separator: 0)
var b = 0
for li in a {
if (li.count > b) {
b = li.count
}
}
return b
}
}
分享