-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCountNumberOfArithmeticTriplets.java
44 lines (38 loc) · 1.27 KB
/
CountNumberOfArithmeticTriplets.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*https://leetcode.com/problems/number-of-arithmetic-triplets/*/
class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
int count = 0;
HashMap<Integer,TreeSet<Integer>> map = new HashMap<Integer,TreeSet<Integer>>();
for (int i = 0; i < nums.length; ++i)
{
if (!map.containsKey(nums[i]))
map.put(nums[i],new TreeSet<Integer>());
map.get(nums[i]).add(i);
}
for (int i = 0; i < nums.length-2; ++i)
{
if (map.containsKey(nums[i]+diff) && map.containsKey(nums[i]+(2*diff)))
{
Integer j = map.get(nums[i]+diff).higher(i);
if (j == null) continue;
Integer k = map.get(nums[j]+diff).higher(j);
if (k != null) ++count;
}
}
return count;
}
}
class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
boolean [] visited = new boolean [201];
for (int num : nums)
visited[num] = true;
int result = 0;
for (int i = diff; i <= 200-diff; ++i)
{
if (visited[i] && visited[i-diff] && visited[i+diff])
++result;
}
return result;
}
}