forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
odd-even-jump.cpp
69 lines (64 loc) · 2.05 KB
/
odd-even-jump.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
int oddEvenJumps(vector<int>& A) {
vector<int> idx(A.size());
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(),
[&](int a, int b) {
return A[a] != A[b] ? A[a] < A[b] : a < b;
});
const auto& next_higher = findNext(idx);
sort(idx.begin(), idx.end(),
[&](int a, int b) {
return A[a] != A[b] ? A[a] > A[b] : a < b;
});
const auto& next_lower = findNext(idx);
vector<bool> odd(A.size()), even(A.size());
odd.back() = even.back() = true;
for (int i = A.size() - 2; i >= 0; --i) {
if (next_higher[i] != -1) {
odd[i] = even[next_higher[i]];
}
if (next_lower[i] != -1) {
even[i] = odd[next_lower[i]];
}
}
return count(odd.cbegin(), odd.cend(), true);
}
private:
vector<int> findNext(const vector<int>& idx) {
vector<int> result(idx.size(), -1);
vector<int> stack;
for (const auto& i : idx) {
while (!stack.empty() && stack.back() < i) {
result[stack.back()] = i, stack.pop_back();
}
stack.emplace_back(i);
}
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
int oddEvenJumps(vector<int>& A) {
vector<bool> odd(A.size()), even(A.size());
odd.back() = even.back() = true;
map<int, int> reachables{{A.back(), A.size() - 1}};
for (int i = A.size() - 2; i >= 0; --i) {
auto high = reachables.lower_bound(A[i]);
if (high != reachables.cend()) {
odd[i] = even[high->second];
}
auto low = reachables.upper_bound(A[i]);
if (low != reachables.cbegin()) {
even[i] = odd[prev(low)->second];
}
reachables[A[i]] = i;
}
return count(odd.cbegin(), odd.cend(), true);
}
};