LeetCode one question per day 55. Description of double hundred efficiency C / C ++ of jumping game
Hello everybody, my name is official Qi Jie (qí guān jié), drip CSDN recorded in the course of learning, time flies, the future can be expected, fueling ~ blog address is: Qi Jie's official blog , Qi Jie's official blog 2 .
topic
Medium difficulty
Given an array of non-negative integers, you are initially in the first position of the array.
Each element in the array represents the maximum length you can jump at that position.
Determine if you can reach the last position.
Example 1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
Example 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
Solution 1: Greed
We can use greedy to solve this problem. We use a variable position
to record the maximum position that can be reached, and then traverse the array from 0 to find the maximum position that can be reached when walking to each position. The maximum position is greater than n-1, you can go to the end, we return true
, if after the end of the traversal still does not reach the end, you can not reach the end, that is, return false
.
The complete solution code is:
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int position = 0;
for (int i = 0; i < n; ++i) {
if (i <= position) {
position = max(position, i + nums[i]);
if (position >= n - 1) {
return true;
}
}
}
return false;
}
};
The execution efficiency of the greedy algorithm at this time is:
The execution efficiency of the greedy algorithm in this question is already very high, so I do n’t plan to think about other solutions further. Friends can share if there is a better solution.
Hello everybody, my name is official Qi Jie (qí guān jié), drip CSDN recorded in the course of learning, time flies, the future can be expected, fueling ~ blog address is: Qi Jie's official blog , Qi Jie's official blog 2 .