Leetcode485. 最大连续1的个数
题目:
给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
题解:
- 用一个计数器 count 记录 1 的数量,另一个计数器 maxCount 记录当前最大的 1 的数量。
- 当我们遇到 1 时,count 加一。
- 当我们遇到 0 时:将 count 与 maxCount 比较,maxCoiunt 记录较大值。将 count 设为 0。
- 返回 maxCount。
scala代码:
/**
*
* @param nums
* @return
*/
def findMaxConsecutiveOnes(nums: Array[Int]): Int = {
var count = 0
var maxCount = 0
for (i <- 0 until nums.length) {
if (nums(i) == 1) {
count = count + 1
} else {
maxCount = math.max(count, maxCount)
count = 0
}
}
math.max(count, maxCount)
}
LeetCode 485最大连续1的个数解析
本文详细解析了LeetCode上的485题——最大连续1的个数,通过一个计数器跟踪连续1的数量,并用另一个计数器记录遇到的最大连续1的数量。使用Scala代码实现解决方案,适用于所有二进制数组输入。
208

被折叠的 条评论
为什么被折叠?



