You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/1500-1599/1550.Three Consecutive Odds/README_EN.md
+88-35Lines changed: 88 additions & 35 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -51,7 +51,15 @@ Given an integer array <code>arr</code>, return <code>true</code> if there
51
51
52
52
<!-- solution:start -->
53
53
54
-
### Solution 1
54
+
### Solution 1: Iteration + Counting
55
+
56
+
We use a variable $\text{cnt}$ to record the current count of consecutive odd numbers.
57
+
58
+
Next, we iterate through the array. If the current element is odd, then $\text{cnt}$ is incremented by one. If $\text{cnt}$ equals 3, then return $\text{True}$. If the current element is even, then $\text{cnt}$ is reset to zero.
59
+
60
+
After the iteration, if three consecutive odd numbers are not found, then return $\text{False}$.
61
+
62
+
The time complexity is $O(n)$, where $n$ is the length of the array $\text{arr}$. The space complexity is $O(1)$.
55
63
56
64
<!-- tabs:start -->
57
65
@@ -61,13 +69,13 @@ Given an integer array <code>arr</code>, return <code>true</code> if there
function threeConsecutiveOdds(arr:number[]):boolean {
137
146
let cnt =0;
138
-
for (const v ofarr) {
139
-
if (v&1) {
140
-
++cnt;
147
+
for (const x ofarr) {
148
+
if (x&1) {
149
+
if (++cnt==3) {
150
+
returntrue;
151
+
}
141
152
} else {
142
153
cnt=0;
143
154
}
144
-
if (cnt==3) {
145
-
returntrue;
146
-
}
147
155
}
148
156
returnfalse;
149
157
}
@@ -155,7 +163,13 @@ function threeConsecutiveOdds(arr: number[]): boolean {
155
163
156
164
<!-- solution:start -->
157
165
158
-
### Solution 2
166
+
### Solution 2: Iteration + Bitwise Operation
167
+
168
+
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.
169
+
170
+
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 $\text{True}$; otherwise, return $\text{False}$.
171
+
172
+
The time complexity is $O(n)$, where $n$ is the length of the array $\text{arr}$. The space complexity is $O(1)$.
159
173
160
174
<!-- tabs:start -->
161
175
@@ -164,20 +178,59 @@ function threeConsecutiveOdds(arr: number[]): boolean {
0 commit comments