您的位置:首页 > 其它

lintcode/leetcode由易至难第13题:Max Consecutive Ones

2017-06-08 14:29 369 查看
Problem:

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.

Code:

public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int count2 = 0;
for(int i = 0; i < nums.length; i++){
if (nums[i] == 0){
count2 = 0;
}
if (nums[i] == 1){
count2 += 1;
}
count = Math.max(count,count2);
}
return count;
}
}


Code2:

public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int count2 = 0;
for(int n : nums){
count = Math.max(count,count2 = n == 0 ? 0 : count2 + 1); //高手倾向于用增强型for循环和三目运算符写
}
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: