您的位置:首页 > 其它

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次数在数组的最后。

代码:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: