leetcode485. max consecutive ones count sum 总结

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

1
2
3
4
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

my code in cpp

思路是对的,但是总觉得我写出这么恶心的代码出来是要被别人打的。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int (vector<int>& nums) {
if (nums.empty()) return 0;
int _fast = 0, _slow = 0,sign=0, _max = 0;
while(_fast!=nums.size())
{
if (nums[_fast] == 1)
{
if (sign == 0)
{
_slow == _fast;
sign = 1;
}

}
else
{
_slow = _fast +1;
sign = 0;
}
_max = max(_fast - _slow + 1, _max);
_fast++;
}
return _max;
}

count

LC in cpp1

1
2
3
4
5
6
7
8
9
10
int (vector<int>& nums) {
if (nums.empty()) return 0;
int _max=0,count=0;
for(auto const &num : nums)
{
if(num==1) _max=max(++count,_max);
else count=0;
}
return _max;
}

sum

比较聪明的方法。利用二进制的性质,只包含0,1。连续1的个数就是连续1的和,遇到0就清空。

LC in cpp2

1
2
3
4
5
6
7
8
9
10
int (vector<int>& nums) {
if (nums.empty()) return 0;
int _max=0,count=0;
for(auto const &num : nums)
{
if(num==1) _max=max(++count,_max);
else count=0;
}
return _max;
}

总结

1