Leetcode刷题(Max Consecutive Ones)

来源:互联网 发布:ubuntu 16 安装Unity 编辑:程序博客网 时间:2024/06/16 10:00

问题描述:Given a binary array, find the maximum number of consecutive 1s in this array.

即 找到二进制数组中最多的连续1的个数。

Input: [1,1,0,1,1,1]Output: 3Explanation: 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

原理流程见图片


根据流程图,代码很简单就可以得出:

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        int n=0,n1=0;        for(int x=0;x<nums.length;x++)        {            if (nums[x]==1)            {                n1++;            }            else if(nums[x]==0)            {                if(n1>n)                {                    n=n1;                    n1=0;                }                else n1=0;            }        }        return n>n1?n:n1;    }}
return采用三元运算表达式简化结果。


Submission Result: Accepted


1 0
原创粉丝点击