【算法學習】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;
}

糾錯

解體的時候,走進了誤區(qū),嘗試去計算 nums 指針指向的數(shù)組的長度,發(fā)現(xiàn)不能計算,因為只有一個指針是沒法判斷長度的,后來發(fā)現(xiàn)題目的參數(shù)給出了長度。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,927評論 0 33
  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員),僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 18,395評論 2 36
  • subset-DFS+Backtracking系列,有模板方法可以記 例1:leetcode 78. Subse...
    暗黑破壞球嘿哈閱讀 5,932評論 1 3
  • 170828 很早起床,完全靠著意識支撐著體力。 送LULU和佳美去火車站的路上,一直感受不到送別的心情。一路都在...
    XxXxXxN閱讀 234評論 0 1
  • 基本上整8月的夜讀時間都給了以前收集的動效文章,讀完后發(fā)現(xiàn)文章質(zhì)量良莠不齊,干貨文有幾篇,空話文也不少。趁今天有空...
    Fog_li閱讀 463評論 0 6

友情鏈接更多精彩內(nèi)容