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.)
The key idea is that every time we jump, we should jump to a position which enable us to jump to the farthest point we in the future.
Here is the explanation:
Given that we are at position i and nums[i], we can jump to any position in the range of [i+1, i + nums[i] ]. Which of those positions should we jump to?
One example: 2,3,1,0,1,4.
When we are at position 0, our range is position 1 and 2. If we jump to 3, we will have the next farthest point = 3+1 = 4. If we jump to 1, we will have the next farthest point 2 + 1 = 3. Both jump takes 1 step. Of course we should select to jump to 3, since 3 would enable us to jump to the farthest point.
So now the idea is to jump to a position, within our current range, which enables us to jump to the farthest point in the next jump. And the farthest point we could jump to is defined as range(position) + position = nums[position] + position. At first I made a mistake and defined the farthest point = nums[position].
Code:
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.empty() || nums.size() == 1) return 0;
int jump_count = 0;
int cur_ind = 0;
while(nums[cur_ind] + cur_ind < nums.size() - 1){
int temp_max_ind = cur_ind+1;//record the index which enables us to jump to the farthest point
for(int i = 1; i <= nums[cur_ind]; i++){//check within the range of current position
if(nums[cur_ind + i] + cur_ind+i >= nums[temp_max_ind]+temp_max_ind)
temp_max_ind = cur_ind+i; //if cur_ind + i position provides a further point we could jump to, record it.
if(nums[cur_ind + i] + cur_ind+i >= nums.size() - 1){//if cur_ind+i position could jump to the destination,
<span style="white-space:pre"> </span>//we immediately jump to this position and jump to the destination. It takes 2 jumps.
jump_count += 2;
return jump_count;
}
}
jump_count ++;
cur_ind = temp_max_ind;//jump to the next optimal postion
}
jump_count++;//remember when loops are over, we are still at cur_ind < destination. Thus we have to jump from cur_ind to destination and it takes 1 jump.
return jump_count;
}
};