题目地址:
https://www.lintcode.com/problem/max-consecutive-ones/description
给定一个 0 − 1 0-1 0−1数组 A A A,找到最长的只含 1 1 1的子数组,返回其长度。
代码如下:
public class Solution {
/**
* @param nums: a binary array
* @return: the maximum number of consecutive 1s
*/
public int findMaxConsecutiveOnes(int[] nums) {
// Write your code here
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
int j = i;
while (j < nums.length && nums[j] == 1) {
j++;
}
res = Math.max(res, j - i);
i = j - 1;
}
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。