1. 程式人生 > >Max Consecutive Ones---LeetCode485

Max Consecutive Ones---LeetCode485

題目描述

Given a binary array, find the maximum number of consecutive 1s in this array.
求最長連續1的個數:給定一個二進位制陣列,求出最長連續的1的個數
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.

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。

解法

分析:
1)求最長連續的1的個數,很簡單的題,卻被我複雜化了….;
2)從陣列初始位置開始,若是1,length變成1,陣列中有1,length++,同時比較maxlength與length的長度;若沒有1,則length置為0,nums[i]繼續往後移動。

public int findMaxConsecutiveOnes1(int[] nums){
        int maxlength=0;
        int length=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==1
){ length++; if(maxlength<length){ maxlength=length; } }else{ length=0; } } return maxlength; }