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;
}
};
'알고리즘' 카테고리의 다른 글
Finding 3-Digit Even Numbers (1) | 2025.05.12 |
---|---|
Minimum Equal Sum of Two Arrays After Replacing Zeros (1) | 2025.05.12 |
Count Number of Balanced Permutations (1) | 2025.05.10 |
Find Minimum Time to Reach Last Room II (1) | 2025.05.08 |
Find Minimum Time to Reach Last Room I (0) | 2025.05.07 |