First blog!
Let's start with this short interesting one.
Problem:
Find the max length of consecutive ones in a "01" vector.
Thinking process:
1. 0s divide 1s. So ++count of 1s while num == 1, reset it to 0 while num == 0. Update the ans to max each time.
2. To decrease comparison times: If 1s are more frequent than 0s, we can update ans whenever we meet a 0; but need one more update after traversing the vector.
3. On the contrary, If 0s are more frequent, update ans while num == 1.
4. Corner case: vector is empty => 0
Let's start with this short interesting one.
Problem:
Find the max length of consecutive ones in a "01" vector.
Thinking process:
1. 0s divide 1s. So ++count of 1s while num == 1, reset it to 0 while num == 0. Update the ans to max each time.
2. To decrease comparison times: If 1s are more frequent than 0s, we can update ans whenever we meet a 0; but need one more update after traversing the vector.
3. On the contrary, If 0s are more frequent, update ans while num == 1.
4. Corner case: vector is empty => 0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int findMaxConsecutiveOnes(vector<int>& nums) { | |
int ans = 0, cur = 0; | |
for (auto &num : nums) { | |
if (num == 1) { | |
ans = max(ans, ++cur); | |
} else { | |
cur = 0; | |
} | |
} | |
return ans; | |
} |
No comments:
Post a Comment