題目描述 - 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;
}
糾錯(cuò)
解體的時(shí)候,走進(jìn)了誤區(qū),嘗試去計(jì)算 nums 指針指向的數(shù)組的長度,發(fā)現(xiàn)不能計(jì)算,因?yàn)橹挥幸粋€(gè)指針是沒法判斷長度的,后來發(fā)現(xiàn)題目的參數(shù)給出了長度。