-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathProblem55_jumpGame.java
More file actions
70 lines (62 loc) · 2.14 KB
/
Problem55_jumpGame.java
File metadata and controls
70 lines (62 loc) · 2.14 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.longluo.top100;
/**
* 55. 跳跃游戏
* <p>
* 给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
* 数组中的每个元素代表你在该位置可以跳跃的最大长度。
* 判断你是否能够到达最后一个下标。
* <p>
* 示例 1:
* 输入:nums = [2,3,1,1,4]
* 输出:true
* 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
* <p>
* 示例 2:
* 输入:nums = [3,2,1,0,4]
* 输出:false
* 解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
* <p>
* 提示:
* 1 <= nums.length <= 3 * 10^4
* 0 <= nums[i] <= 10^5
* <p>
* https://leetcode.com/problems/jump-game/
*/
public class Problem55_jumpGame {
// Brute Force time: O(n^2) space: O(n)
public static boolean canJump_bf(int[] nums) {
int len = nums.length;
boolean[] visited = new boolean[len];
visited[0] = true;
for (int i = 0; i < len; i++) {
int steps = nums[i];
if (visited[i] && steps > 0) {
for (int j = 1; j <= steps && i + j < len; j++) {
visited[i + j] = true;
}
}
}
return visited[len - 1];
}
// Greedy time: O(n) space: O(1)
public static boolean canJump_greedy(int[] nums) {
int len = nums.length;
int maxIdx = 0;
for (int i = 0; i < len; i++) {
int steps = nums[i];
if (maxIdx >= i) {
maxIdx = Math.max(maxIdx, i + steps);
if (maxIdx >= len - 1) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
System.out.println("true ?= " + canJump_bf(new int[]{2, 3, 1, 1, 4}));
System.out.println("true ?= " + canJump_greedy(new int[]{2, 3, 1, 1, 4}));
System.out.println("true ?= " + canJump_greedy(new int[]{2, 0}));
System.out.println("false ?= " + canJump_greedy(new int[]{3, 2, 1, 0, 4}));
}
}