짬뽕얼큰하게의 맨땅에 헤딩 :: Three Consecutive Odds

summary

  • Given an integer array, return true if there are three consecutive odd numbers in the array, otherwise return false.

approach

  • The solution uses a counter to keep track of the number of consecutive odd numbers
  • It iterates over the array, incrementing the counter whenever it encounters an odd number and resetting it whenever it encounters an even number
  • If the counter reaches 3, it immediately returns true
  • If it iterates over the entire array without finding three consecutive odd numbers, it returns false.

complexity

  • O(n) where n is the number of elements in the array

explain

  • The solution has a time complexity of O(n) because it makes a single pass over the array
  • The space complexity is O(1) because it uses a constant amount of space to store the counter.

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;
    }
};
블로그 이미지

짬뽕얼큰하게

,