您的位置:首页 > 其它

LeetCode 485 Max Consecutive Ones 最大连续1的个数

2017-11-05 22:48 513 查看
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

题目描述

给定只含0,1的数组,在数组中返回连续的1的最大个数

解题思路

遍历一遍数组,用count记录当前1的个数,如果为1,则count加1,否则count为0,num记录现有连续1的最大个数。

/* C++ */
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
if(nums.size() == 0) return 0;
int count = 0;
int num = 0;
for(int i = 0;i < nums.size(); i++){
if(nums[i] == 1)
count++;
else{

count = 0;
}
num = max(num,count);
}
return num;

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