55. Jump Game
Description
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.Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
My solution(python):
解题思路:利用贪心算法,每次在可到达的条件下,取最远的末尾的位置,并同时判断是否达到列表的末尾。
class Solution:
def canJump(self, nums):
end = 0
for index in range(0, len(nums)):
if index <= end:
if index + nums[index] >= len(nums) - 1:
return True
end = max(end, index + nums[index])
else:
return False
return False
45. Jump Game II
Description
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.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
Note: You can assume that you can always reach the last index.
My solution:
解题思路:
同样利用贪心算法。因为需要算出最少的步数,所以这题中需要的是在每个下标时预测下一次能够跳到的最远距离。
利用nextMAX来记录同一步数不同选择的情况下,下一次能跳到的最远下标。然后再将它赋给currentMAX来跳一下步。这里需要注意,每次的下标i不能超过currentMAX.
//第一次使用了c++来写,这种方法用队列实现BFS,遍历了所有情况,选出最先的,较容易理解,不过效率会低一些。
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
vector<int> dist(n, -1);
queue<int> q;
q.push(0);
dist[0] = 0;
while (!q.empty())
{
int u = q.front();
q.pop();
if (u == n - 1)
return dist[u];
for (int i = nums[u]; i >= 1; i--)
{
if (u + i < n && dist[u + i] == -1)
{
if (u + i == n - 1)
return dist[u] + 1;
q.push(u + i);
dist[u + i] = dist[u] + 1;
}
}
}
}
};
#python贪心算法
class Solution:
def jump(self, nums):
if len(nums) == 1: return 0
currentMAX = 0
nextMAX = 0
i = 0
steps = 0
while(i <= currentMAX):
steps += 1
while(i <= currentMAX):
nextMAX = max(nums[i] + i, nextMAX)
if(nextMAX >= len(nums) - 1):
return steps
i += 1
currentMAX = nextMAX