Description
Given a binary array, find the maximum number of consecutive 1s in this array.
Example:
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
Analysis
解法一:循环查找连续全1子序列,以全1子序列的首尾座标的差(程序中是以全0子序列的首-全1子序列的首得到的)中的最大值作为结果。
解法二:思路类似,全1子序列的元素的和就是长度,故直接不断循环求和比较即可。
解法三:思路同解法二,区别在于利用a * 1 = a
,a * 0 = 0
这样的特点,用乘法代替了if分支,循环体行数减少。
Code
Version 1
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int i = 0, result = 0, temp = 0;
while (i < nums.size()){
while (nums[i] == 0 && i < nums.size()) i++;
temp = i;
while (nums[i] == 1) i++;
result = max(result, i - temp);
}
return result;
}
};
Version 2
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int result = 0, temp = 0;
for (int i = 0; i < nums.size(); i++){
if (nums[i] == 1){
temp++;
result = max(result, temp);
}
else temp = 0;
}
return result;
}
};
Version 3
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int result = 0, temp = 0;
for (int i = 0; i < nums.size(); i++){
temp = (temp + nums[i]) * nums[i];
result = max(result, temp);
}
return result;
}
};
Appendix
- Link: https://leetcode.com/problems/max-consecutive-ones/
- Run Time:
- Version 1: 46ms
- Version 2: 35ms / 52ms / 36ms
- Version 2: 46ms
I ran Version 2 three times and got three different results…