-
Notifications
You must be signed in to change notification settings - Fork 0
/
JumpGame.java
87 lines (80 loc) · 2.13 KB
/
JumpGame.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
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
80
81
82
83
84
85
86
87
// https://leetcode.com/problems/jump-game/
// #array #greedy
/*
class Solution {
public boolean canJump(int[] nums) {
int lastStep = nums.length - 1;
if (lastStep == 0) return true;
if (nums[0] >= lastStep) return true;
int i = 0;
while(i <= lastStep) {
int maxCurStep = i + nums[i];
int nextStep = maxCurStep, jumpPos = i;
for (int j = i+1 ; j <= maxCurStep ; j++) {
if (j + nums[j] >= nextStep) {
nextStep = j + nums[j];
jumpPos = j;
}
}
if (nextStep >= lastStep) return true;
if (i == jumpPos) return false;
i = jumpPos;
}
return false;
}
}
*/
/* BETTER WAY
i ----------------------i
j--------------------------------n
--------------------------------
---------------
class Solution {
public boolean canJump(int[] nums) {
int lastStep = nums.length - 1;
if (lastStep == 0) return true;
if (nums[0] >= lastStep) return true;
int i = 0;
int maxCurStep = i + nums[i];
while(i <= lastStep) {
int temp = maxCurStep;
for (int j = i+1 ; j <= temp ; j++) {
if (j + nums[j] >= maxCurStep) {
maxCurStep = j + nums[j];
}
}
if (maxCurStep >= lastStep) return true;
if (i == temp) return false;
i = temp;
}
return false;
}
}
*/
/*
BEST WAY
maxCurStep = 0
for i = 0 .. lastStep:
if i > maxCurStep:
-> False
maxCurStep = max(maxCurStep, i + nums[i])
return maxCurStep >= lastStep
*/
class Solution {
public boolean canJump(int[] nums) {
int lastStep = nums.length - 1;
if (lastStep == 0) return true;
if (nums[0] >= lastStep) return true;
int maxCurStep = 0;
for (int i = 0; i <= lastStep; i++) {
if (i > maxCurStep) {
return false;
}
maxCurStep = Math.max(maxCurStep, i + nums[i]);
}
if (maxCurStep >= lastStep) {
return true;
}
return false;
}
}