알고리즘
Three Consecutive Odds
짬뽕얼큰하게
2025. 5. 11. 12:28
Leetcode Problem:
Summary
- Check if there are three consecutive odd numbers in an array
Approach
- Use a counter to track the consecutive odd numbers
- If the counter reaches 3, return true
- Otherwise, return false after iterating through the entire array.
Complexity
- O(n) where n is the number of elements in the array
Explanation
- The solution iterates through the array once, using a counter to track the consecutive odd numbers
- If an odd number is found, the counter is incremented
- If an even number is found, the counter is reset to 0
- If the counter reaches 3, the function returns true immediately
- If the loop completes without finding three consecutive odd numbers, the function returns false.
Solution Code:
class Solution {
public:
bool threeConsecutiveOdds(vector& arr) {
int cnt = 0;
for(int i = 0 ; i < arr.size(); i++){
if(arr[i] & 1){
cnt++;
} else {
cnt = 0;
}
if (cnt >= 3) return true;
}
return false;
}
};
class Solution {
public:
bool threeConsecutiveOdds(vector& arr) {
int cnt = 0;
for(int i = 0 ; i < arr.size(); i++){
if(arr[i] & 1){
cnt++;
} else {
cnt = 0;
}
if (cnt >= 3) return true;
}
return false;
}
};