网站不同颜色,文创产品营销方案,百度免费推广怎么做,深圳市建设交易网官解#xff1a; 为了得到数组中最大连续 111 的个数#xff0c;需要遍历数组#xff0c;并记录最大的连续 111 的个数和当前的连续 111 的个数。如果当前元素是 111#xff0c;则将当前的连续 111 的个数加 111#xff0c;否则#xff0c;使用之前的连续 111 的个数更新… 官解 为了得到数组中最大连续 111 的个数需要遍历数组并记录最大的连续 111 的个数和当前的连续 111 的个数。如果当前元素是 111则将当前的连续 111 的个数加 111否则使用之前的连续 111 的个数更新最大的连续 111 的个数并将当前的连续 111 的个数清零。 遍历数组结束之后需要再次使用当前的连续 111 的个数更新最大的连续 111 的个数因为数组的最后一个元素可能是 111且最长连续 111 的子数组可能出现在数组的末尾如果遍历数组结束之后不更新最大的连续 111 的个数则会导致结果错误。 刚开始做的答案
class Solution {public int findMaxConsecutiveOnes(int[] nums) {int count 0;for(int i 0;i nums.length;i ){if(nums[i] 1){count;if(nums[i1] ! 1){System.out.println(count);}}}System.out.println(count);return count;}} 最后正确的答案
class Solution {public int findMaxConsecutiveOnes(int[] nums) {int count 0;int maxCount 0;for(int i 0;i nums.length;i ){if(nums[i] 1){count;}else{maxCount Math.max(maxCount,count);count 0;}}maxCount Math.max(maxCount,count);return maxCount;}}