LeetCode 485. Max Consecutive Ones (最长连续1)
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
and1
. - The length of input array is a positive integer and will not exceed 10,000
题目标签:Array
题目给了我们一个nums array, 里面只会出现0和1, 让我们找到一个最长连续1的长度。
这题很简单,只要维护一个maxCount 就可以了,再设一个count,遇到1的时候,count++;遇到0的时候,把count 和 maxCount 中挑大的继续保存,更新count = 0。
注意,最后遍历完,如果最后一段是1的话,还需要维护maxCount一次
Java Solution:
Runtime beats 70.20%
完成日期:05/10/2017
关键词:Array
关键点:维护一个maxCount
1 public class Solution 2 { 3 public int findMaxConsecutiveOnes(int[] nums) 4 { 5 int maxCount = 0; 6 int count = 0; 7 8 for(int i=0; i<nums.length; i++) 9 { 10 if(nums[i] == 1) // count consecutive ones 11 count++; 12 else if(nums[i] == 0) // if reach 0, save large count into maxCount 13 { 14 maxCount = Math.max(maxCount, count); 15 count = 0; // update count to 0 16 } 17 18 } 19 // check the last consecutive ones 20 maxCount = Math.max(maxCount, count); 21 22 return maxCount; 23 } 24 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?