Given a binary array, find the maximum number of consecutive 1s in this array.
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
and1
. - The length of input array is a positive integer and will not exceed 10,000
题意:找出数组中连续为1的长度n;
思路:
1.遍历数组,创建一个计数器和一个结果result,如果数组元素等于1,则count++;求出result和count的最大值赋值为result,否则count=0;重新开始计数;
2.巧妙利用0乘于任何数等于0的事实;
1.代码实现:
class Solution { public int findMaxConsecutiveOnes(int[] nums) { int count = 0; int result = 0; int len = nums.length; for(int i = 0;i < len; i++){ if(nums[i]==1){ count++; //计数器 result = Math.max(count,result); result和count的最大值 }else{ count = 0; } } return result; } }
2.代码实现:
int findMaxConsecutiveOnes(int* nums, int numsSize) { int i; int sum = 0,max = 0; for(i = 0;i<numsSize;i++){ sum =(sum + nums[i])*nums[i]; //求出sum值,sum相当于计数器 if(max<sum){ max = sum; } } return max; }
所有评论(0)