問題(Easy):
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
大意:
給出一個二進制數組,在數組中找到連續的1最大的長度。
例1:
輸入:[1,1,0,1,1,1]
輸出:3
解釋:開頭兩個數字和最后三個數字是連續的1。
最大的連續的1是3個。注意:
- 輸入的數組只包含0和1。
- 輸入數組的長度是個正整數且不超過10000。
思路:
無非就是遍歷數組,檢查連續的1,用一個臨時變量記錄每次連續的1的個數,連續結束時判斷是否比最大的連續個數要大。
代碼的寫法可以有很多種,也會隨著寫法不同帶來一些效率差異,但時間復雜度是一樣的。
代碼(C++):
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int res = 0;
int temp = 0;
bool flag = true;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 1) {
if (flag) temp++;
else {
temp = 1;
flag = true;
}
if (temp > res) res = temp;
} else
if (flag) flag = false;
}
return res;
}
};
合集:https://github.com/Cloudox/LeetCode-Record