485. Max Consecutive Ones

来源:互联网 发布:手机p2p软件下载 编辑:程序博客网 时间:2024/06/05 19:51

问题: Given a binary array, find the maximum number of consecutive 1s in this array.
问题分析: 需要找到二进制数组中最大的连续1的数量。想到用双循环来解决这个题目,但是犯了一个需要注意的错误。

class Solution {         public int findMaxConsecutiveOnes(int[] nums) {                         int count = 0;                         int  i = 0;                         int max = 0;                         for( ; i < nums.length; ++i){                             for(; i < nums.length&& nums[i] == 1 ; ++i){//刚开始将nums[i] == 1写在前面,这就会导致数组访问范围外;这种正确的写法用短路性质保证了nums[i]不会访问数组之外的值。                                 count++;                             }                             if(max < count) max = count;                             count = 0;                         }                         return max;                    }}
原创粉丝点击