Skip to content

Commit 0dd77ec

Browse files
committed
Sync LeetCode submission Runtime - 1 ms (94.90%), Memory - 17.8 MB (74.08%)
1 parent d7c5ff1 commit 0dd77ec

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<div class="example-block">
7+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
8+
9+
<p><strong>Output:</strong> <span class="example-io">1</span></p>
10+
11+
<p><strong>Explanation:</strong></p>
12+
13+
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
14+
</div>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<div class="example-block">
19+
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
20+
21+
<p><strong>Output:</strong> <span class="example-io">0</span></p>
22+
23+
<p><strong>Explanation:</strong></p>
24+
25+
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
26+
</div>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>3 &lt;= nums.length &lt;= 100</code></li>
33+
<li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li>
34+
</ul>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Approach: One Time Traversal
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def countSubarrays(self, nums: List[int]) -> int:
8+
ans = 0
9+
10+
for i in range(1, len(nums) - 1):
11+
if nums[i] == (nums[i - 1] + nums[i + 1]) * 2:
12+
ans += 1
13+
14+
return ans
15+
16+

0 commit comments

Comments
 (0)