Posted onEdited onInLeetCodeDisqus: Symbols count in article: 627Reading time ≈1 mins.
O(n) time O(1) space followup for infinite stream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intfindMaxConsecutiveOnes(vector<int>& nums){ int res = 0, c0 = 0, c1 = 0; for (int x : nums) { if (x == 1) { ++c0; ++c1; } else { c1 = c0 + 1; c0 = 0; } res = max(res, c1); } return res; } };
找最长的子数组最多只包含一个0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intfindMaxConsecutiveOnes(vector<int>& nums){ int res = 0; for (int l = 0, r = 0, cnt = 0, n = size(nums); r < n; ++r) { if (nums[r] == 0) { ++cnt; } while (cnt > 1) { if (nums[l] == 0) { --cnt; } ++l; } res = max(res, r - l + 1); } return res; } };