题目:
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
and1
. - The length of input array is a positive integer and will not exceed 10,000
思路:
一道练手题目。不过看到网上写的代码真的很精妙,所以再贴一下。但是两个代码的时间复杂度都是O(n),空间复杂度都是O(1)。
代码:
1、一般解法:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int max_num = 0, num = 0;
bool started = false;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == 1) {
if (!started) {
started = true;
num = 1;
}
else {
++num;
}
}
else {
if (started) {
max_num = max(max_num, num);
started = false;
num = 0;
}
}
}
return max(max_num, num);
}
};
2、精妙解法:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int ret = 0, sum = 0;
for (int i = 0; i < nums.size(); ++i) {
sum = (sum + nums[i] ) * nums[i];
ret = max(ret, sum);
}
return ret;
}
};