Skip to content

Commit

Permalink
Merge pull request #116 from Lisanaaa/master
Browse files Browse the repository at this point in the history
Update jump-game-ii.py
  • Loading branch information
kamyu104 authored Mar 28, 2018
2 parents 5cd5fbf + 95bfeb9 commit 9a2ac6f
Showing 1 changed file with 2 additions and 42 deletions.
44 changes: 2 additions & 42 deletions Python/jump-game-ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
#

# not pass on leetcode because of time limit
class Solution:
class Solution(object):
# @param A, a list of integers
# @return an integer
def jump(self, A):
Expand All @@ -29,47 +29,7 @@ def jump(self, A):
jump_count += 1
reachable = max(reachable, i + length)
return jump_count

# Time: O(n^2)
# Space: O(1)
class Solution2:
# @param A, a list of integers
# @return an integer
def jump(self, A):
result, prev_reachable, reachable = 0, -1, 0
while reachable > prev_reachable:
if reachable >= len(A) - 1:
return result
result += 1
prev_reachable = reachable
for i, length in enumerate(A[:reachable + 1]):
reachable = max(reachable, i + length)
return -1

# when you on an index of nums, move to next index which can move farthest in range of this index reachable
# Time: O(log(n))
# Space: O(1)
class Solution3(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums[-1] = 2 ** 31
nums2, l = [i + j for i, j in enumerate(nums)], len(nums) - 1

def find_max_index(index):
tmp = nums2[index:index + nums[index] + 1]
return index + tmp.index(max(tmp))

index, steps = 0, 0
while True:
index = find_max_index(index)
if index:
steps += 1
if index == l:
break
return steps


if __name__ == "__main__":
print Solution().jump([2,3,1,1,4])
Expand Down

0 comments on commit 9a2ac6f

Please sign in to comment.