【String-easy】485. Max Consecutive Ones 返回最多有多少个连续的1

1. 题目原址

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

2. 题目描述

在这里插入图片描述

3. 题目大意

给定一个一维数组,返回数组中连续1 的个数,返回最长的连续1的个数

4. 解题思路

定义两个变量,一个是当前连续1的个数local,一个是返回的最长的连续1的个数retMax

5. AC代码

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int retMax = 0;
        int local = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == 1)
                local ++;
            else {
                local = 0;
            }
            retMax = Math.max(retMax,local);
        }
        return retMax;
    }
}

6. 相似题型

【1】Max Consecutive Ones II 题目原址:https://leetcode.com/problems/max-consecutive-ones-ii/
【2】 1004. Max Consecutive Ones III 题目原址:https://leetcode.com/problems/max-consecutive-ones-iii/

猜你喜欢

转载自blog.csdn.net/xiaojie_570/article/details/92763940