Skip to content

Commit ecd7f7b

Browse files
refactor 403
1 parent 2d8d7a8 commit ecd7f7b

File tree

1 file changed

+30
-27
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+30
-27
lines changed

src/main/java/com/fishercoder/solutions/_403.java

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -50,37 +50,40 @@
5050
*/
5151
public class _403 {
5252

53-
/**Reference: https://discuss.leetcode.com/topic/59903/very-easy-to-understand-java-solution-with-explanations/2
54-
* and https://leetcode.com/articles/frog-jump/#approach-5-using-dynamic-programmingaccepted*/
55-
public boolean canCross(int[] stones) {
56-
if (stones.length == 0) {
57-
return true;
58-
}
59-
Map<Integer, Set<Integer>> map = new HashMap<>(stones.length);
60-
map.put(0, new HashSet<>());
61-
map.get(0).add(1);
62-
for (int i = 1; i < stones.length; i++) {
63-
map.put(stones[i], new HashSet<>());
64-
}
53+
public static class Solution1 {
54+
/**
55+
* Reference: https://discuss.leetcode.com/topic/59903/very-easy-to-understand-java-solution-with-explanations/2
56+
* and https://leetcode.com/articles/frog-jump/#approach-5-using-dynamic-programmingaccepted
57+
*/
58+
public boolean canCross(int[] stones) {
59+
if (stones.length == 0) {
60+
return true;
61+
}
62+
Map<Integer, Set<Integer>> map = new HashMap<>(stones.length);
63+
map.put(0, new HashSet<>());
64+
map.get(0).add(1);
65+
for (int i = 1; i < stones.length; i++) {
66+
map.put(stones[i], new HashSet<>());
67+
}
6568

66-
for (int i = 0; i < stones.length; i++) {
67-
int stone = stones[i];
68-
for (int step : map.get(stone)) {
69-
int reach = step + stone;
70-
if (reach == stones[stones.length - 1]) {
71-
return true;
72-
}
73-
Set<Integer> set = map.get(reach);
74-
if (set != null) {
75-
set.add(step);
76-
if (step - 1 > 0) {
77-
set.add(step - 1);
69+
for (int i = 0; i < stones.length; i++) {
70+
int stone = stones[i];
71+
for (int step : map.get(stone)) {
72+
int reach = step + stone;
73+
if (reach == stones[stones.length - 1]) {
74+
return true;
75+
}
76+
Set<Integer> set = map.get(reach);
77+
if (set != null) {
78+
set.add(step);
79+
if (step - 1 > 0) {
80+
set.add(step - 1);
81+
}
82+
set.add(step + 1);
7883
}
79-
set.add(step + 1);
8084
}
8185
}
86+
return false;
8287
}
83-
return false;
8488
}
85-
8689
}

0 commit comments

Comments
 (0)