problem Ⅰ
55. Jump Game
You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Input: nums = [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: nums = [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.
solution 1
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==1)return true;
if(!nums[0])return false;
for(int i=1; i<nums.size()-1; i++){
nums[i] = max(nums[i], nums[i-1]-1);
if(!nums[i])return false;
}
return nums[nums.size()-2];
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
space complexity
:
O
(
1
)
O(1)
O(1)
solution 2
class Solution {
public:
bool canJump(vector<int>& nums) {
int i = 0;
for (int reach = 0; i < nums.size() && i <= reach; ++i)
reach = max(i + nums[i], reach);
return i == nums.size();
}
};
problem Ⅱ
45. Jump Game II
Given an array of non-negative integers nums, 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.
You can assume that you can always reach the last index.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
solution
class Solution {
public:
int jump(vector<int>& nums) {
int currBegin=0, currEnd=0, currFar=0, jumps=0;
for(int i=0; i<nums.size()-1; i++){
currFar = max(currFar, i + nums[i]);
if(i==currEnd){
++jumps;
currEnd = currFar;
}
}
return jumps;
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
space complexity
:
O
(
1
)
O(1)
O(1)
NOTE:
the main idea is based on greedy, at first the range of the current jump is [currBegin, currEnd]
, currFar
is the farthest we can jump by the element in the current range.
once the i
meet the currEnd
, which means that we have iterate all element in the current range, and we get the currFar
that we can jump from the begin in the current range, and we set the new currEnd
equals to currFar
, then keep the above steps, finally we can get the ans.