-
Notifications
You must be signed in to change notification settings - Fork 28
/
Jump_Game_II.cpp
49 lines (46 loc) · 1.37 KB
/
Jump_Game_II.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
class Solution {
public:
/* BFS style (Accepted)
int jump(int A[], int n) {
if(n < 2) return 0;
int source = 0;
queue < pair<int, int> > Queue;
Queue.push(make_pair(source, 0));
vector<bool> visited(n, false);
visited[0] = true;
while(!Queue.empty()) {
int indx = Queue.front().first;
int steps = Queue.front().second;
if(indx >= n - 1) return steps;
for(int i = A[indx]; i > 0; --i) {
int idx = indx + i;
if(idx >= n - 1) return steps + 1;
if(!visited[idx]) {
visited[idx] = true;
Queue.push(make_pair(idx, steps + 1));
}
}
Queue.pop();
}
return -1;
}
*/
int jump(vector<int>& A) {
int n = (int)A.size();
if(n < 2) return 0;
int steps = 0;
for(int i = 0; i < n; ) {
int maxDistance = A[i] + i;
steps++;
if (maxDistance >= n - 1) return steps;
int tmp = 0;
for (int j = i + 1; j <= maxDistance; j++) {
if (j + A[j] > tmp) {
tmp = A[j] + j;
i = j;
}
}
}
return steps;
}
};