leetcode 485.最大连续1的个数 JavaScript

发布日期:

这题就很简单了,直接 for 循环,判断是 1 就给 temp +1 然后到 0 之后就判断是否是最大 然后 temp 置 0

如果最后一个元素是1的话 是跳不到else里的,所以需要在最后 比较一下 temp 和 ans

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function(nums) {
    if (nums.length===1) return nums[0] === 0 ? 0 : 1 
    let ans = temp = 0 
    for(let i = 0; i < nums.length; i++) {
        if (nums[i] == 1) {
            temp++
        } else {
            if (temp > ans) {
                ans = temp
            }
            temp = 0
        }
    }
    if(temp>ans) ans=temp
    return ans
};

Max Consecutive Ones

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,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:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注