-
Notifications
You must be signed in to change notification settings - Fork 0
/
JumpGameII.hpp
79 lines (66 loc) · 1.24 KB
/
JumpGameII.hpp
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
70
71
72
73
74
75
76
77
78
79
//Jump Game II
//
//Given an array of non - negative integers, you are initially positioned at the first index
//of the array.
//
//Each element in the array represents your maximum jump length at that position.
//
//Your goal is to reach the last index in the minimum number of jumps.
//
//For example :
//Given array A = [2, 3, 1, 1, 4]
//
//The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1,
//then 3 steps to the last index.)
#include <climits>
class Solution {
public:
//int jump(int A[], int n)
//{
//
// if (0 == n && 1 == n)
// return 0;
// A[n - 1] = 0;
// for (int i = n - 1; i > -1; i--)
// {
// if (A[i] != 0)
// A[i] = min(&A[i]+1, A[i]) + 1;
// }
// return A[0];
//}
//
//int min(int A[], int n)
//{
// int min = INT_MAX;
// int i = 0;
// while (i < n)
// {
// if (A[i] < min)
// min = A[i];
// i++;
// }
// return min;
//}
int jump(int A[], int n)
{
if (0 == n || 1 == n)
return 0;
int steps = 0;
int range = 0;
int max_index = 0;
for (int i = 0; i < n; i++)
{
if (i > range)
{
range = max_index;
++steps;
}
max_index = max(max_index, i + A[i]);
}
return steps;
}
int max(int a, int b)
{
return a > b ? a : b;
}
};