【算法学习】C Max Consecutive Ones

题目描述 - 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 指针指向的数组的长度,发现不能计算,因为只有一个指针是没法判断长度的,后来发现题目的参数给出了长度。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,984评论 2 36
  • subset-DFS+Backtracking系列,有模板方法可以记 例1:leetcode 78. Subse...
    暗黑破坏球嘿哈阅读 5,898评论 1 3
  • 170828 很早起床,完全靠着意识支撑着体力。 送LULU和佳美去火车站的路上,一直感受不到送别的心情。一路都在...
    XxXxXxN阅读 187评论 0 1
  • 基本上整8月的夜读时间都给了以前收集的动效文章,读完后发现文章质量良莠不齐,干货文有几篇,空话文也不少。趁今天有空...
    Fog_li阅读 426评论 0 6