This is a Leetcode problem:
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.
Note:
You can assume that you can always reach the last index.
Here is my first solution to this problem:
def jump(nums):
n = len(nums)
curr_far = min(nums[0], n - 1)
next_far = 0
step = 0
for i in range(n):
if i <= curr_far:
if next_far < i + nums[i]:
next_far = min(i + nums[i], n - 1)
if i == curr_far and curr_far != 0:
curr_far = next_far
step += 1
return step
nums = #Enter a list.
print(jump(nums))
Here is an example of an input/output:
nums = [2,3,1,1,4]
>>> 2
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.
Here is my second solution to this problem:
class Solution:
def __init__(self, nums):
self.nums = nums
def jump(self, nums):
if not nums or len(nums) == 1:
return 0
curr = 0
count = 0
while(curr < len(nums)):
maxReach = -1
index = 0
for i in range(1, nums[curr] + 1):
if curr + i >= len(nums) - 1:
return count + 1
else:
if nums[curr + i] + i > maxReach:
maxReach = nums[curr + i] + i
index = curr + i
curr = index
count += 1
nums = #Enter a list.
game = Solution(nums)
print(game.jump(nums))
Input/output - Same as above.
So, I would like to have a code review for the efficiency of both the programs.
Any help would be highly appreciated.