lintcode/leetcode由易至难第13题:Max Consecutive Ones

来源:互联网 发布:宏观审慎管理知乎 编辑:程序博客网 时间:2024/06/05 08:41

Problem:

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

Example 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.
Code:

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        int count = 0;        int count2 = 0;         for(int i = 0; i < nums.length; i++){            if (nums[i] == 0){                count2 = 0;            }            if (nums[i] == 1){                count2 += 1;            }            count = Math.max(count,count2);        }        return count;    }}


Code2:

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        int count = 0;        int count2 = 0;        for(int n : nums){            count = Math.max(count,count2 = n == 0 ? 0 : count2 + 1); //高手倾向于用增强型for循环和三目运算符写        }        return count;    }}

原创粉丝点击