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

    My idea:for循环遍历,最后退出循环的时候也要判断,因为为1的时候我不能去给max赋值

    class Solution:
        def findMaxConsecutiveOnes(self, nums):
            count=0
            max=0
            for i in nums[::]:
                if(i==1):
                    count=count+1
                if(i==0):
                    if(max<count):
                        max=count
                    count=0
            if (max < count):
                max = count
            return max

    那用双指针怎么做呢,参考一下别人的,主要就是从slow开始数,fast往前跑,跑完一个循环给slow,就这样迭代

    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 0;
            
            int slow = 0;
            int fast = 0;
            int end = nums.length;
            
            while (slow < end) {
                fast = slow;
                int count = 0;
                while (fast < end && nums[fast++] == 1) {
                    count++;
                }
                max = Math.max(max,count);
                slow = fast;
            }
            
            return max;
        }
    }

    ok 我试着用pyhton写一遍

    class Solution:
        def findMaxConsecutiveOnes(self, nums):
    
            m = 0
            a = 0
            b = 0
            end = len(nums)
            while (a < end):
                b = a
                count = 0
                while (nums[b] == 1):
                    count = count + 1
                    b = b + 1
                    if(b==end):
                        break
                m = max(m, count)
                a = b
            return m

    ok,超出时间限制555

  • 相关阅读:
    curl上传图片文件
    手工制作简单后台模板
    首页自动生成静态化html
    svn-多个项目版本库和自动同步更新post-commit
    Snoopy+phpquery采集demo
    phpstorm使用手册
    mac系统使用帮助
    upupw一键绿色免安装环境包
    去掉文件夹的.svn文件
    centos安装svn服务器
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10827595.html
Copyright © 2011-2022 走看看