leetcode485最大连续1的个数

leetcode 485 Max Consecutive Ones

Posted by BY on August 13, 2020

前言

持续更新了

正文

问题来源

本问题来自leetcode上的485题。

问题描述

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

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

分析:

func findMaxConsecutiveOnes(nums []int) int {
    i := 0
    max := 0
    for i < len(nums) {
        count := 0
        for i<len(nums)&&nums[i] == 1 {
            count++
            i++
        }
        if count > max {
            max = count
        }
        i++
    }
    return max
}
class Solution {
  public int findMaxConsecutiveOnes(int[] nums) {
    int count = 0;
    int maxCount = 0;
    for(int i = 0; i < nums.length; i++) {
      if(nums[i] == 1) {
        // Increment the count of 1's by one.
        count += 1;
      } else {
        // Find the maximum till now.
        maxCount = Math.max(maxCount, count);
        // Reset count of 1.
        count = 0;
      }
    }
    return Math.max(maxCount, count);
  }
}

总结:

勤思考。

结语

不管怎么样好好加油。