485. 最大连续1的个数(JavaScript)

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

示例 1:

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

注意:

  • 输入的数组只包含 0 和1
  • 输入数组的长度是正整数,且不超过 10,000。

思路:

时间按复杂度:O(n)

设置一个计数变量 count,来计数连续出现的 1。

从头到尾遍历,若为 1,count++,若为0,求max与count的最大值,count变为0.

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function(nums) {
  var max = 0,
      count = 0;
  for (var i in nums) {
    if (nums[i] === 1) {
      count++;
    } else {
      max = Math.max(count, max);
      count = 0;
    }
  }
  max = Math.max(count, max);  // 最后一连串的 1 有可能是最长的
  return max;
};

猜你喜欢

转载自blog.csdn.net/romeo12334/article/details/81456453