【leetcode】485. 最大连续1的个数(max-consecutive-ones)(模拟)[简单]

链接

https://leetcode-cn.com/problems/max-consecutive-ones/

耗时

解题:3 min
题解:9 min

题意

给定一个二进制数组, 计算其中最大连续1的个数。

思路

计数数组中连续 1 的长度,遍历数组,以当前元素为结尾的最大连续 1 的个数为 tmp,tmp 的最大值即为答案。详见代码。

时间复杂度: O ( n ) O(n) O(n)

AC代码

class Solution {
    
    
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
    
    
        int n = nums.size();
        int ans = 0, tmp = 0;
        for(int i = 0; i < n; ++i) {
    
    
            if(nums[i] == 1) {
    
    
                tmp++;
            }
            else {
    
    
                ans = max(ans, tmp);
                tmp = 0;
            }
        }
        ans = max(ans, tmp);
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/Krone_/article/details/113817470
今日推荐