Jump Game(LeetCode)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/80960033

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.

元素代表当前位置能跳的最大步数,问能不能跳到最后一个位置。

思路:1.用一个mark记录每一次可以到达的路径,看最后一个是不是true

class Solution {
public:
	bool canJump(vector<int>& nums) {
		vector<bool> mark(nums.size(), false);
		for (int i = 0; i <= nums[0]; i++) {
			mark[i] = true;
		}
		for (int i = 1; i < nums.size(); i++) {
			if (mark.back())
				return true;
			if (mark[i]) {
				for (int j = 0; j <= nums[i]; j++) {
					mark[i + j] = true;
				}
			}
		}
		return mark.back();
	}
};

2.做一个简化,依次往后,只要记住当前位置能跳到的最大位置就可以了,如果下一个位置比前一个位置能跳到的最大位置还大,就失败。

class Solution {
public:
	bool canJump(vector<int>& nums) {
		int max = 0;
		for (int i = 0; i < nums.size(); i++) {
			if (i > max) 
				return false;
			max = std::max(i + nums[i], max);
		}
		return true;
	}
};



猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80960033