leetCode-Max Consecutive Ones

来源:互联网 发布:linux项目部署 编辑:程序博客网 时间:2024/05/22 01:43

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

Example1:

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

My Solution:

class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        int count = 0;        int maxN = 0;        for(int i : nums){            if(i == 1){                count++;                 if(count > maxN){                    maxN = count;                }            }else{                count = 0;            }        }        return maxN;    }}

改进:

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        int result = 0;        int count = 0;        for (int i = 0; i < nums.length; i++) {            if (nums[i] == 1) {                count++;                //替换为了Math.max()函数,更简洁                result = Math.max(count, result);            }            else count = 0;        }        return result;    }}

总结:
注意每次碰到1的时候增加count,然后求max(count,maxN),然后每次num = 0将count置0就可以了。

原创粉丝点击