Skip to content

Commit fdd9f3b

Browse files
authored
Create number-of-arithmetic-triplets.py
1 parent eb245fd commit fdd9f3b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# hash table
5+
class Solution(object):
6+
def arithmeticTriplets(self, nums, diff):
7+
"""
8+
:type nums: List[int]
9+
:type diff: int
10+
:rtype: int
11+
"""
12+
lookup = set(nums)
13+
return sum((x-diff in lookup) and (x-2*diff in lookup) for x in nums)
14+
15+
16+
# Time: O(n)
17+
# Space: O(n)
18+
import collections
19+
20+
21+
# dp
22+
class Solution2(object):
23+
def arithmeticTriplets(self, nums, diff):
24+
"""
25+
:type nums: List[int]
26+
:type diff: int
27+
:rtype: int
28+
"""
29+
result = 0
30+
cnt1 = collections.Counter()
31+
cnt2 = collections.Counter()
32+
for x in nums:
33+
result += cnt2[x-diff]
34+
cnt2[x] += cnt1[x-diff]
35+
cnt1[x] += 1
36+
return result

0 commit comments

Comments
 (0)