File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Question Link: https://leetcode.com/problems/frog-jump/
3+ * Primary idea: Dynamic Programming, a dictionary to keep all steps that the position
4+ * can jump, and a dp array to keep max step that the position can take
5+ * Time Complexity: O(n^2), Space Complexity: O(1)
6+ *
7+ */
8+
9+ class FrogJump {
10+ func canCross( _ stones: [ Int ] ) -> Bool {
11+ guard stones. count > 1 else {
12+ return true
13+ }
14+
15+ var indexSteps = [ Int : Set < Int > ] ( ) , maxStep = Array ( repeating: 0 , count: stones. count)
16+ var k = 0
17+
18+ insert ( & indexSteps, 0 , 0 )
19+
20+ for i in 1 ..< stones. count {
21+ while maxStep [ k] + 1 < stones [ i] - stones[ k] {
22+ k += 1
23+ }
24+ for j in k ..< i {
25+ let distance = stones [ i] - stones[ j]
26+
27+ if let steps = indexSteps [ j] , steps. contains ( distance - 1 ) || steps. contains ( distance) || steps. contains ( distance + 1 ) {
28+
29+ insert ( & indexSteps, distance, i)
30+ maxStep [ i] = max ( maxStep [ i] , distance)
31+ }
32+ }
33+ }
34+
35+ return maxStep. last! > 0
36+ }
37+
38+ private func insert( _ dict: inout [ Int : Set < Int > ] , _ num: Int , _ index: Int ) {
39+ if dict [ index] != nil {
40+ dict [ index] !. insert ( num)
41+ } else {
42+ var set = Set < Int > ( )
43+ set. insert ( num)
44+ dict [ index] = set
45+ }
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments