題目描述 - 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ù)給出了長度肃廓。