comments | difficulty | edit_url | tags | |
---|---|---|---|---|
true |
简单 |
|
给定一个二进制数组 nums
, 计算其中最大连续 1
的个数。
示例 1:
输入:nums = [1,1,0,1,1,1] 输出:3 解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
示例 2:
输入:nums = [1,0,1,1,0,1] 输出:2
提示:
1 <= nums.length <= 105
nums[i]
不是0
就是1
.
我们可以遍历数组,用一个变量
当遍历到一个 1 时,将
遍历结束后,返回
时间复杂度
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
ans = cnt = 0
for x in nums:
if x:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x == 1) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
}
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x) {
ans = max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
};
func findMaxConsecutiveOnes(nums []int) (ans int) {
cnt := 0
for _, x := range nums {
if x == 1 {
cnt++
ans = max(ans, cnt)
} else {
cnt = 0
}
}
return
}
function findMaxConsecutiveOnes(nums: number[]): number {
let [ans, cnt] = [0, 0];
for (const x of nums) {
if (x) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
impl Solution {
pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let mut ans = 0;
let mut cnt = 0;
for &x in nums.iter() {
if x == 1 {
cnt += 1;
ans = ans.max(cnt);
} else {
cnt = 0;
}
}
ans
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function (nums) {
let [ans, cnt] = [0, 0];
for (const x of nums) {
if (x) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
};
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function findMaxConsecutiveOnes($nums) {
$ans = $cnt = 0;
foreach ($nums as $x) {
if ($x == 1) {
$cnt += 1;
$ans = max($ans, $cnt);
} else {
$cnt = 0;
}
}
return $ans;
}
}