Skip to content

Commit 2d7be6b

Browse files
author
王俊超
committed
commit
1 parent 40579a3 commit 2d7be6b

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 使用贪心算法,每次都移动最远的距离
3+
*
4+
* @author: wangjunchao(王俊超)
5+
* @time: 2018-09-28 15:27
6+
**/
7+
public class Solution {
8+
9+
public int jump(int[] nums) {
10+
11+
if (nums == null || nums.length < 2) {
12+
return 0;
13+
}
14+
15+
// 记录跳跃次数
16+
int jump = 0;
17+
// 记录当前可以到达的最远的位置
18+
int currentMax = 0;
19+
// 下一次可以到达的最远的位置
20+
int nextMax = 0;
21+
// 记录处理的位置
22+
int i = 0;
23+
24+
// 还没有到最未位置,还可以移动
25+
while (currentMax - i + 1 > 0) {
26+
// 跳数增加
27+
jump++;
28+
// 找下一次最远可以移动的位置
29+
for (; i <= currentMax; i++) {
30+
nextMax = Math.max(nextMax, nums[i] + i);
31+
// 如果下一次可以移动到最末的位置,则返回跳数
32+
if (nextMax >= nums.length - 1) {
33+
return jump;
34+
}
35+
}
36+
37+
// 本次处理不能使移动位增加,并且不能到达最末位置,说明永远到不了最后的位置
38+
if (currentMax == nextMax) {
39+
return Integer.MAX_VALUE;
40+
}
41+
42+
// 更新当前可以移动的最远位置
43+
currentMax = nextMax;
44+
}
45+
46+
return 0;
47+
}
48+
49+
}

0 commit comments

Comments
 (0)