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…