当前位置:网站首页>LeetCode_485_最大连续1的个数
LeetCode_485_最大连续1的个数
2022-08-08 03:21:00 【Fitz1318】
题目链接
题目描述
给定一个二进制数组 nums , 计算其中最大连续 1 的个数。
示例 1:
输入:nums = [1,1,0,1,1,1]
输出:3
解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
示例 2:
输入:nums = [1,0,1,1,0,1]
输出:2
提示:
1 <= nums.length <= 10^5nums[i]不是0就是1.
解题思路
- 记录最大的连续1的个数
ans和当前的连续的1的个数now - 如果当前元素是1,则
now++,否则使用之前的连续的1的个数更新ans,并令now = 0 - 遍历数组结束之后,需要再次使用
now来更新ans,因为数组的最后一个元素可能是1,且最长连续1的子数组可能出现在数组的末尾,如果遍历数组结束之后不更新ans,则会导致结果错误
AC代码
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0;
int now = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
now++;
} else {
ans = Math.max(ans, now);
now = 0;
}
}
ans = Math.max(ans, now);
return ans;
}
}
边栏推荐
- egg-validate-custom validation method error language (error Chinese prompt)
- Nanny level tutorial!Golang microservices simple architecture in practice
- 栈的压入、弹出序列
- easypoi custom template export
- json工具类
- The conceptual framework of consciousness: does our consciousness arise from attentional schemas?
- Enterprise learning (11) to build the main branch, trigger, nailing notice
- 机器学习笔记 - 基于CNN+OpenCV的图像着色
- From hardcover to smartcover, the next wave is emerging. Listen to what smart home gurus have to say?
- 模拟登录——添加cookies,使用postmanget请求网页数据
猜你喜欢
随机推荐
巧记硬链接与软链接
Flume (三) --------- Flume 进阶
The futures company how to validate the normality of opening an account
Docker安装Redis 6.2.6
杭电多校-Map-(模拟退火)
【STM32】标准库-看门狗
From hardcover to smartcover, the next wave is emerging. Listen to what smart home gurus have to say?
文本生成介绍
egg-session 将数据存储到redis
新手使用 go channel 需要注意的问题
关于 globalThis is not defined 报错问题
Build a personal network disk using z-file and Qiniu cloud object storage
Several daily LeetCode exercises
如何验证期货公司开户的正规性
使用z-file和七牛云对象存储构建个人网盘
Bluetooth att gatt agreement
CGAN theory explanation and code implementation
PC博物馆(番外01)-城会玩,初中生开发实体尺规大航海游戏
Mysql整行增删改查
NVIDIA NCCL优化——利用共享内存实现比NCCL更快的集合通信







