|
1 | 1 | package com.fishercoder.solutions; |
2 | 2 |
|
3 | | -/**Given an array of non-negative integers, you are initially positioned at the first index of the array. |
4 | | -
|
5 | | - Each element in the array represents your maximum jump length at that position. |
6 | | -
|
7 | | - Determine if you are able to reach the last index. |
8 | | -
|
9 | | - For example: |
10 | | - A = [2,3,1,1,4], return true. |
11 | | -
|
12 | | - A = [3,2,1,0,4], return false.*/ |
| 3 | +/** |
| 4 | + * 55. Jump Game |
| 5 | + * |
| 6 | + * Given an array of non-negative integers, you are initially positioned at the first index of the array. |
| 7 | + * Each element in the array represents your maximum jump length at that position. |
| 8 | + * Determine if you are able to reach the last index. |
| 9 | + * |
| 10 | + * For example: |
| 11 | + * A = [2,3,1,1,4], return true. |
| 12 | + * A = [3,2,1,0,4], return false.*/ |
13 | 13 | public class _55 { |
14 | 14 |
|
15 | | - public static boolean canJump_greedy(int[] nums) { |
16 | | - int farthest = nums[0]; |
17 | | - for (int i = 0; i < nums.length; i++) { |
18 | | - if (i <= farthest && nums[i] + i > farthest) { |
19 | | - //i <= farthest is to make sure that this current i is within the current range |
20 | | - // nums[i]+i > farthest is to make sure that it's necessary to update farthest with current nums[i]+i |
21 | | - farthest = nums[i] + i; |
22 | | - } |
23 | | - } |
24 | | - return farthest >= nums.length - 1; |
25 | | - } |
26 | | - |
27 | | - //this normal dp ends in TLE for extreme test cases |
28 | | - public static boolean canJump_dp(int[] nums) { |
29 | | - boolean[] can = new boolean[nums.length]; |
30 | | - can[0] = true; |
31 | | - for (int i = 0; i < nums.length; i++) { |
32 | | - int reach = nums[i]; |
33 | | - if (can[i]) { |
34 | | - for (int j = i + 1; j < nums.length && j <= i + reach; j++) { |
35 | | - can[j] = true; |
| 15 | + public static class Solution1 { |
| 16 | + public boolean canJump(int[] nums) { |
| 17 | + int farthest = nums[0]; |
| 18 | + for (int i = 0; i < nums.length; i++) { |
| 19 | + if (i <= farthest && nums[i] + i > farthest) { |
| 20 | + //i <= farthest is to make sure that this current i is within the current range |
| 21 | + // nums[i]+i > farthest is to make sure that it's necessary to update farthest with current nums[i]+i |
| 22 | + farthest = nums[i] + i; |
36 | 23 | } |
37 | 24 | } |
| 25 | + return farthest >= nums.length - 1; |
38 | 26 | } |
39 | | - return can[nums.length - 1]; |
40 | | - } |
41 | | - |
42 | | - public static void main(String... strings) { |
43 | | -// int[] nums = new int[]{1,2}; |
44 | | - int[] nums = new int[]{0, 2, 3}; |
45 | | - System.out.println(canJump_greedy(nums)); |
46 | 27 | } |
47 | 28 | } |
0 commit comments