-
SLPH一趟遍历+计数器:
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ ans = cnt = 0 for n in nums: if n == 1: cnt += 1 ans = max(ans, cnt) else: cnt = 0 return ans
-
SLPH由于是个二进制数组,所以数组中的数字只能是0或1,那么连续1的和跟个数相等,所以我们可以计算和,通过加上num,再乘以num来计算,如果当前数字是0,那么sum就被重置为0,还是要更新结果res,参见代码如下:
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int res = 0, sum = 0; for (int num : nums) { sum = (sum + num) * num; res = max(res, sum); } return res; } };
-
SLPH向量法:
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { vector<int> cnt(nums.size()); cnt[0] = nums[0]; int maxn = 0; for(int i = 1; i < nums.size(); i++){ if(nums[i] == 0){ cnt[i] = 0; maxn = max(maxn, cnt[i-1]); } else { cnt[i] = cnt[i-1] + 1; } } maxn = max(maxn, cnt[nums.size() - 1]); return maxn; } };
-