Skip to content

Commit 885b48d

Browse files
authored
Create number-of-arithmetic-triplets.cpp
1 parent fdd9f3b commit 885b48d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/number-of-arithmetic-triplets.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// hash table
5+
class Solution {
6+
public:
7+
int arithmeticTriplets(vector<int>& nums, int diff) {
8+
unordered_set<int> lookup(cbegin(nums), cend(nums));
9+
return accumulate(cbegin(nums), cend(nums), 0, [&](const auto& total, const auto&x) {
10+
return total + lookup.count(x - diff) * lookup.count(x - 2 * diff);
11+
});
12+
}
13+
};
14+
15+
// Time: O(n)
16+
// Space: O(n)
17+
// dp
18+
class Solution2 {
19+
public:
20+
int arithmeticTriplets(vector<int>& nums, int diff) {
21+
int result = 0;
22+
unordered_map<int, int> cnt1, cnt2;
23+
for (const auto& x : nums) {
24+
result += cnt2[x - diff];
25+
cnt2[x] += cnt1[x - diff];
26+
++cnt1[x];
27+
}
28+
return result;
29+
}
30+
};

0 commit comments

Comments
 (0)