美文网首页
【算法学习】C Max Consecutive Ones

【算法学习】C Max Consecutive Ones

作者: Jiubao | 来源:发表于2017-01-25 10:59 被阅读26次

题目描述 - leetcode

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 and 1.
The length of input array is a positive integer and will not exceed 10,000

C 解答

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int maxCount = 0;
    
    if (numsSize <= 0) {
        return 0;
    }
    
    int currentCount = 0;
    
    for (int i=0; i<numsSize; i++) {
        if (nums[i] == 0) {
            if (currentCount > maxCount) {
                maxCount = currentCount;
            }
            
            currentCount = 0;
        } else {
            currentCount += 1;
        }
        
        if ((i == numsSize - 1) && (currentCount > 0)) {
            if (currentCount > maxCount) {
                maxCount = currentCount;
            }
        }
    }
    
    return maxCount;
}

纠错

解体的时候,走进了误区,尝试去计算 nums 指针指向的数组的长度,发现不能计算,因为只有一个指针是没法判断长度的,后来发现题目的参数给出了长度。

相关文章

网友评论

      本文标题:【算法学习】C Max Consecutive Ones

      本文链接:https://www.haomeiwen.com/subject/adptittx.html