LeetCode 485. 最大连续1的个数 Max Consecutive Ones

【题目描述】
给定一个二进制数组, 计算其中最大连续1的个数。
【示例】

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

【思路】
1、变量count记录1的个数 max记录count的最大值
2、遍历遇0,max(max,count), count=0
3、返回max
4、时间复杂度O(n)
5、空间复杂度O(1)

Swift代码实现:

func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {//[1,0,1,1,0,1]
    var count = 0
    var res = 0
    for n in nums {
        if n == 0 {
            count = 0
        } else {
            count+=1
            res = max(count, res)
        }
    }
    return res
}

C语言实现:

int findMaxConsecutiveOnes(int* nums, int numsSize){
    int res = 0;
    int count = 0;
    for (int i = 0; i res) {
            res = count;
        }
    }
    return res;
}

你可能感兴趣的:(LeetCode 485. 最大连续1的个数 Max Consecutive Ones)