LeetCode 485. Max Consecutive Ones
2017-04-10 15:18
465 查看
题目描述:
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 and 1.
The length of input array is a positive integer and will not exceed 10,000
思路:
计算数组中连续1个数的最大值。
max来记录1的出现次数最大值 ,count用来计连续出现1的次数。如果当前不为0,count加1,否则取max和count大的那个赋给max,并将count重新置0。最后返回max和count中大的那个,因为有可能出现0一次都没出现,或者最大的连续1次数在数组的最后。
代码:
输出结果: 36ms
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 and 1.
The length of input array is a positive integer and will not exceed 10,000
思路:
计算数组中连续1个数的最大值。
max来记录1的出现次数最大值 ,count用来计连续出现1的次数。如果当前不为0,count加1,否则取max和count大的那个赋给max,并将count重新置0。最后返回max和count中大的那个,因为有可能出现0一次都没出现,或者最大的连续1次数在数组的最后。
代码:
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int len=nums.size();//计算nums的长度 int max=0;//记录最大值 int count=0;//用来计连续出现1的次数 for(int i=0;i<len;++i){ if(nums[i]!=0){//如果当前不为0 ++count;//1的次数加1 } else{ max=max>count?max:count;//max取max和count大的那个 count=0;//将count重新置0 } } return max>count?max:count;//返回max和count中大的那个 } };
输出结果: 36ms
相关文章推荐
- LeetCode 485. Max Consecutive Ones (最长连续1)
- leetcode 485. Max Consecutive Ones python
- 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
- 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
- leetcode 485. Max Consecutive Ones
- 485. Max Consecutive Ones leetcode array
- LeetCode 485. Max Consecutive Ones
- Leetcode:485. Max Consecutive Ones 找二进制串连续1最多是多少
- Leetcode485. Max Consecutive Ones
- python--leetcode485. Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones (边界处理)