【算法學習】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,776評論 0 33
  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員),僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 17,941評論 2 36
  • subset-DFS+Backtracking系列,有模板方法可以記 例1:leetcode 78. Subse...
    暗黑破壞球嘿哈閱讀 5,896評論 1 3
  • 170828 很早起床,完全靠著意識支撐著體力。 送LULU和佳美去火車站的路上,一直感受不到送別的心情。一路都在...
    XxXxXxN閱讀 179評論 0 1
  • 基本上整8月的夜讀時間都給了以前收集的動效文章,讀完后發現文章質量良莠不齊,干貨文有幾篇,空話文也不少。趁今天有空...
    Fog_li閱讀 425評論 0 6