最少跳数到达末尾(Jump Game)

第一题:判断是否能跳到最后

55. Jump Game

My Submissions
Question Editorial Solution
Total Accepted: 74643  Total Submissions: 265245  Difficulty: Medium

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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Subscribe to see which companies asked this question















最少跳数到达末尾(Jump Game)_第1张图片

第一题代码:

class Solution
{
public:
    bool canJump(vector<int>& nums)
    {
        int curMax = 0;     //从 0~i 这 i+1 个元素中能达到的最大范围
        
        for (int i = 0; i < nums.size(); ++i)
        {
            /* 当 curMax < i 时,说明经过前面的元素无法达到 i 及其后面的位置
             * 直接返回false */
            if (curMax < i)
                return false;
            curMax = max(curMax, nums[i] + i);
        }
        return true;
    }
};

第二题:以最少跳数跳到最后

int jump(vector<int>& nums) {
	int minJumps = 0;  //minJumps 为目前为止的跳数
 	int curMax = 0;    //从 0 - i 这个i+1个元素中能达到的最大范围
	int curRich = 0;   //从 nums[0]进行 minJumps 次跳之后能达到的最大范围
	
	for (int i = 0; i < nums.size(); ++i) {
		//minJumps次跳已经不足以到达当前第i个元素
		if (curRich < i) {
			++minJumps;
			curRich = curMax;
		}
		if (i + nums[i] > curMax)
			curMax = i + nums[i];
	}
	return minJumps;
}

你可能感兴趣的:(算法)