【LeetCode】14.Array and String — Max Consecutive Ones 一的
发布时间:2020-12-14 04:44:34 所属栏目:大数据 来源:网络整理
导读:Given a binary array,find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,1]Output: 3Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note:
Given a binary array,find the maximum number of consecutive 1s in this array. Example 1: Input: [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:
考虑时间复杂度,用一次循环完成。设置计数器,当出现1的时候加加,当出现0的时候计数中断,从零开始重新计数,并将之前得到的连续1的个数进行保存。每次只保存连续1的最大个数,放在countermax里面。最后要对边界情况进行特殊处理,具体代码如下: ? class Solution { public: int findMaxConsecutiveOnes(vector<int>&nums) { int size = nums.size(); int counter = 0;//计数器 int counterMax = 0;//保留最大结果 int record = 1;//把1标记一下 for (int i = 0; i < size; i++) { //一次遍历数组 if (record == nums[i]) { //满足条件开始统计 counter++; if (i == size - 1) return counterMax>counter?counterMax:counter; //末尾情况做特殊处理 } else { if (counter > counterMax) { counterMax = counter;//保留最大连续个数 } counter = 0; } } return counterMax; } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |