LeetCode 485. Max Consecutive Ones (最长连续1)
2017-09-21 01:16
393 查看
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
public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int maxCount = 0; int count = 0; for(int i=0; i<nums.length; i++) { if(nums[i] == 1) // count consecutive ones count++; else if(nums[i] == 0) // if reach 0, save large count into maxCount { maxCount = Math.max(maxCount, count); count = 0; // update count to 0 } } // check the last consecutive ones maxCount = Math.max(maxCount, count); return maxCount; } }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
相关文章推荐
- Leetcode 485. Max Consecutive Ones 最大连续1 解题报告
- Leetcode:485. Max Consecutive Ones 找二进制串连续1最多是多少
- 【算法作业1】LeetCode 485. Max Consecutive Ones
- leetcode 485. Max Consecutive Ones
- LeetCode 485 Max Consecutive Ones 最大连续1的个数
- Leetcode 485. Max Consecutive Ones
- python--leetcode485. Max Consecutive Ones
- 【LeetCode】485. Max Consecutive Ones
- leetcode 485. Max Consecutive Ones
- LeetCode -485. Max Consecutive Ones - 思路详解 - C++
- LeetCode 485. Max Consecutive Ones
- [LeetCode]485. Max Consecutive Ones(最大连续为1的数量)
- LeetCode 485. Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones
- [leetcode]: 485. Max Consecutive Ones
- LeetCode-485. Max Consecutive Ones
- 485.Max Consecutive Ones 最大连续1的个数
- 485. Max Consecutive Ones leetcode array
- LeetCode 485. Max Consecutive Ones