leetcode485. Max Consecutive Ones

来源:互联网 发布:java在线 编辑:程序博客网 时间:2024/04/30 03:54

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: 3Explanation: The first two digits or the last three digits are consecutive 1s.    The maximum number of consecutive 1s is 3.

解法一

从头开始计算连续1的长度。

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        if (nums == null || nums.length == 0) {            return 0;        }        int index = 0;        int max = 0;        for (int i = 0; i < nums.length; i++) {            while(i < nums.length && nums[i] == 1) {                index++;                i++;            }            if (index > max) {                max = index;            }            index = 0;        }        return max;    }}

这里写图片描述

解法二

如果是1的话,sum值加1;如果是0,sum变为0,又重新开始计算。

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        if (nums == null || nums.length == 0) {            return 0;        }        int max = 0;        int sum = 0;        for (int i = 0; i < nums.length; i++) {            sum = (sum + nums[i]) * nums[i];            if (sum > max) {                max = sum;            }        }        return max;    }}

这里写图片描述

0 0
原创粉丝点击