comments | difficulty | edit_url | rating | source | tags | |
---|---|---|---|---|---|---|
true |
Easy |
1221 |
Weekly Contest 202 Q1 |
|
Given an integer array arr
, return true
if there are three consecutive odd numbers in the array. Otherwise, return false
.
Example 1:
Input: arr = [2,6,4,1] Output: false Explanation: There are no three consecutive odds.
Example 2:
Input: arr = [1,2,34,3,4,5,7,23,12] Output: true Explanation: [5,7,23] are three consecutive odds.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
We use a variable
Next, we iterate through the array. If the current element is odd, then
After the iteration, if three consecutive odd numbers are not found, then return
The time complexity is
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
cnt = 0
for x in arr:
if x & 1:
cnt += 1
if cnt == 3:
return True
else:
cnt = 0
return False
class Solution {
public boolean threeConsecutiveOdds(int[] arr) {
int cnt = 0;
for (int x : arr) {
if (x % 2 == 1) {
if (++cnt == 3) {
return true;
}
} else {
cnt = 0;
}
}
return false;
}
}
class Solution {
public:
bool threeConsecutiveOdds(vector<int>& arr) {
int cnt = 0;
for (int x : arr) {
if (x & 1) {
if (++cnt == 3) {
return true;
}
} else {
cnt = 0;
}
}
return false;
}
};
func threeConsecutiveOdds(arr []int) bool {
cnt := 0
for _, x := range arr {
if x&1 == 1 {
cnt++
if cnt == 3 {
return true
}
} else {
cnt = 0
}
}
return false
}
function threeConsecutiveOdds(arr: number[]): boolean {
let cnt = 0;
for (const x of arr) {
if (x & 1) {
if (++cnt == 3) {
return true;
}
} else {
cnt = 0;
}
}
return false;
}
Based on the properties of bitwise operations, the result of a bitwise AND operation between two numbers is odd if and only if both numbers are odd. If there are three consecutive numbers whose bitwise AND result is odd, then these three numbers are all odd.
Therefore, we only need to iterate through the array and check if there exists three consecutive numbers whose bitwise AND result is odd. If such numbers exist, return
The time complexity is
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
return any(x & arr[i + 1] & arr[i + 2] & 1 for i, x in enumerate(arr[:-2]))
class Solution {
public boolean threeConsecutiveOdds(int[] arr) {
for (int i = 2, n = arr.length; i < n; ++i) {
if ((arr[i - 2] & arr[i - 1] & arr[i] & 1) == 1) {
return true;
}
}
return false;
}
}
class Solution {
public:
bool threeConsecutiveOdds(vector<int>& arr) {
for (int i = 2, n = arr.size(); i < n; ++i) {
if (arr[i - 2] & arr[i - 1] & arr[i] & 1) {
return true;
}
}
return false;
}
};
func threeConsecutiveOdds(arr []int) bool {
for i, n := 2, len(arr); i < n; i++ {
if arr[i-2]&arr[i-1]&arr[i]&1 == 1 {
return true
}
}
return false
}
function threeConsecutiveOdds(arr: number[]): boolean {
const n = arr.length;
for (let i = 2; i < n; ++i) {
if (arr[i - 2] & arr[i - 1] & arr[i] & 1) {
return true;
}
}
return false;
}