forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jump-game-ii.py
36 lines (33 loc) · 1.07 KB
/
jump-game-ii.py
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
# Time: O(n)
# Space: O(1)
#
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
#
# Each element in the array represents your maximum jump length at that position.
#
# Your goal is to reach the last index in the minimum number of jumps.
#
# For example:
# Given array A = [2,3,1,1,4]
#
# The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
#
# not pass on leetcode because of time limit
class Solution(object):
# @param A, a list of integers
# @return an integer
def jump(self, A):
jump_count = 0
reachable = 0
curr_reachable = 0
for i, length in enumerate(A):
if i > reachable:
return -1
if i > curr_reachable:
curr_reachable = reachable
jump_count += 1
reachable = max(reachable, i + length)
return jump_count
if __name__ == "__main__":
print Solution().jump([2,3,1,1,4])
print Solution().jump([3,2,1,0,4])