-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-JumpGameII.cpp
More file actions
48 lines (36 loc) · 1.29 KB
/
Copy pathLeetCode-JumpGameII.cpp
File metadata and controls
48 lines (36 loc) · 1.29 KB
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
#define INF 100000
struct SegmentTree {
vector<int> T;
SegmentTree(int n) {
T = vector<int>(n * 4, INF);
}
int query_min(int v, int tl, int tr, int l, int r) {
if (l > r) return INF;
if (l == tl && r == tr) return T[v];
int tm = (tl + tr) >> 1;
return min(query_min(v*2, tl, tm, l, min(r, tm)), query_min(v*2+1, tm + 1, tr, max(l, tm + 1), r));
}
void update(int v, int tl, int tr, int pos, int val) {
if (tl == tr) {
T[v] = val;
} else {
int tm = (tl + tr) >> 1;
if (pos <= tm) update(v*2, tl, tm, pos, val);
else update(v*2+1, tm+1, tr, pos, val);
T[v] = min(T[v*2], T[v*2+1]);
}
}
};
class Solution {
public:
int jump(vector<int>& nums) {
SegmentTree tree(nums.size());
tree.update(1, 0, nums.size() - 1, 0, 0);
//O(n*logn)
for (int i = nums.size() - 2; i >= 0; --i) {
if (nums[i] + i >= nums.size() - 1) tree.update(1, 0, nums.size() - 1, i, 1);
else tree.update(1, 0, nums.size() - 1, i, tree.query_min(1, 0, nums.size() - 1, i + 1, i + nums[i]) + 1);
}
return tree.query_min(1, 0, nums.size() - 1, 0, 0);
}
};