zoukankan      html  css  js  c++  java
  • [LeetCode] 485. 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

    最大连续1的个数。

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

    思路是追击型的two pointer,但是我们在实现的时候可以不需要用到指针,详细参见代码。这道题其实也是隐式的滑动窗口类型的题。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int findMaxConsecutiveOnes(int[] nums) {
     3         // corner case
     4         if (nums.length == 0 || nums == null) {
     5             return 0;
     6         }
     7 
     8         // normal case
     9         int max = 0;
    10         int count = 0;
    11         for (int i = 0; i < nums.length; i++) {
    12             if (nums[i] == 1) {
    13                 count++;
    14                 max = Math.max(max, count);
    15             } else {
    16                 count = 0;
    17             }
    18         }
    19         return max;
    20     }
    21 }

    JavaScript实现

     1 /**
     2  * @param {number[]} nums
     3  * @return {number}
     4  */
     5 var findMaxConsecutiveOnes = function (nums) {
     6     let max = 0;
     7     let count = 0;
     8     for (let i = 0; i < nums.length; i++) {
     9         if (nums[i] == 1) {
    10             count++;
    11             max = Math.max(max, count);
    12         } else {
    13             count = 0;
    14         }
    15     }
    16     return max;
    17 };

    sliding window相关题目

    LeetCode 题目总结

  • 相关阅读:
    JSON转JS对象,JS对象转JSON
    java 判断对象是否是某个类的类型两种方法
    关于多线程笔记
    Java 多线程编程
    javaScript正则表达式的使用
    java中正则表达式常用方法
    史上最全常用正则表达式大全
    正则表达式语法
    vue属性值调方法
    POJ-1562 Oil Deposits
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14235498.html
Copyright © 2011-2022 走看看